Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// api/index.js
import Request from 'superagent'
export const getUser (userId) {
return Request
.get('/api/user/:userId');
}
import _ from 'lodash';
export const CURRENT_USER_ID = 1;
export const Factories = {
User (UserId = cuid()) {
return {
'id': UserId,
'username': 'foo',
'password': 'bar',
'lastLogin': 0,
'socialNetworks': [
'twitter',
'facebook',
],
};
},
}
export const DB = {
users: [
Factories.User(CURRENT_USER_ID),
],
};
export const ORM = _.chain(DB);
// api/mocks/errors.js
/**
* Access to resource unauthorised
* @return {Response}
*/
export const ResponseErrorUnauthorised = () => {
return {
status: 401,
content: {
error: 'Not authorised'
}
};
};
// api/mocks/index.js
import mock from 'superagent-mocker';
import faker from 'faker';
import cuid from 'cuid';
import * as DB from './db';
import * as Errors from './errors';
export default (client) => {
const apiRoot = client.apiRoot || 'api';
const Server = mock(client);
/*
* @api {get} /api/user Get user details
* @apiVersion 0.0.1
* @apiName GetUser
* @apiGroup User
* @apiSuccess {String} EmailAddress
* @apiSuccess {Array} SocialNetworks List of connected social networks
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "EmailAddress": "e@ma.il",
* "SocialNetworks": [
* "Twitter",
* "Facebook"
* ]
* }
*
* @apiError ErrorNotAuthorized User isn't logged in
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 401 Not Authorized
* {}
*
* @apiError ErrorNotFound
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 404 Not Found
* {}
*/
Server.get(`${apiRoot}/user`, (request) => {
console.log(`GET:/api/user`, request);
let user = DB.ORM
.get('users')
.find({id: DB.CURRENT_USER_ID })
.value();
if (!user) {
return Errors.ResponseErrorUnauthorised();
}
let response = {
content: user,
headers: request.headers
};
console.log(`GET:/api/user. [response]`, response);
return response;
});
};
// store/actions.js
import api from "../api";
import types from "./types";
export const getUser ({state, dispatch}, userId) {
return api.getUser(userId)
.then( (user) => {
dispatch(types.UPDATE_USER, user);
return;
})
.catch( (err) => {
state.lastError = err;
throw err;
});
};
// store/mutations.js
import types from './types';
export const [types.UPDATE_USER] (state, user) {
state.User = user;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.