Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function() {
- "use strict";
- var token = storage.get("token");
- var isAdmin = false;
- var username = null;
- function call(method, params) {
- params = params || {};
- //Retrieve the callbacks
- var onSuccess = params.onSuccess || noop;
- var onFailure = params.onFailure || noop;
- var onFinish = params.onFinish || noop;
- if(token) params.token = token;
- //Remove them from this object since we will just reuse it later
- delete params['onFinish'];
- delete params['onFailure'];
- delete params['onSuccess'];
- //Call to our server
- $.ajax({
- url: '/api/' + method,
- cache: false,
- dataType: 'json',
- data: params,
- complete: onFinish,
- type: 'POST',
- success: function(data) {
- if(data.success) {
- onSuccess(data.result);
- }
- else {
- onFailure(data);
- }
- },
- error: function() {
- onFailure({
- error: "net_err",
- desc: "Network error"
- });
- }
- });
- }
- function setToken(value) {
- token = value;
- storage.set('token', value);
- }
- function clearToken() {
- token = null;
- storage.set('token', null);
- }
- function noop() {}
- function addTrivialFunction(name) {
- window.nomnom[name] = function(params) {
- return call(name, params);
- }
- }
- var trivialFunctions = [
- 'search',
- 'view_place',
- 'view_menu',
- 'view_food',
- 'pending_places',
- 'pending_foods',
- 'approve_place',
- 'reject_place',
- 'approve_food',
- 'reject_food',
- 'suggest_place',
- 'suggest_food',
- 'edit_place',
- 'edit_food',
- 'remove_place',
- 'remove_food',
- 'add_to_menu',
- 'remove_from_menu',
- 'edit_menu',
- 'rate',
- 'post_review',
- 'view_reviews',
- 'suggested_places',
- 'suggested_foods',
- 'view_profile',
- 'similar_foods'
- ];
- //To export functions from a module, just return an object that includes them
- window.nomnom = {
- //currently, login is quite simple, in the future, we can save the token in the browser after a successful login
- login: function(params) {
- params.password = hex_md5(params.password);
- var userOnSuccess = params.onSuccess || noop;
- params.onSuccess = onSuccess;
- call('login', params);
- function onSuccess(result) {
- username = params.username;
- setToken(result.token);
- userOnSuccess(result);
- }
- },
- register: function(params) {
- params.password = hex_md5(params.password);
- call('register', params);
- },
- logout: function(params) {
- clearToken();
- call('logout', params);
- },
- isLoggedIn: function() {
- return token ? true:false;
- }
- }
- for(var i = 0; i < trivialFunctions.length; ++i)
- addTrivialFunction(trivialFunctions[i]);
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement