added necessary npm packages

This commit is contained in:
Aqeeb Imtiaz Harun
2018-08-09 11:15:09 +08:00
parent 93ee4ecb68
commit fc1b011160
2787 changed files with 243227 additions and 1 deletions
+5
View File
@@ -0,0 +1,5 @@
'use strict';
const bodyParser = require('body-parser');
module.exports = [bodyParser.json({ limit: '10mb', extended: false }), bodyParser.urlencoded({ extended: false })];
+73
View File
@@ -0,0 +1,73 @@
'use strict';
const fs = require('fs');
const path = require('path');
const express = require('express');
const logger = require('morgan');
const cors = require('cors');
const compression = require('compression');
const errorhandler = require('errorhandler');
const objectAssign = require('object-assign');
const bodyParser = require('./body-parser');
module.exports = function (opts) {
const userDir = path.join(process.cwd(), 'public');
const defaultDir = path.join(__dirname, '../../dist');
const staticDir = fs.existsSync(userDir) ? userDir : defaultDir;
opts = objectAssign({ logger: true, static: staticDir }, opts);
const arr = [];
// Compress all requests
if (!opts.noGzip) {
arr.push(compression());
}
// Enable CORS for all the requests, including static files
if (!opts.noCors) {
arr.push(cors({ origin: true, credentials: true }));
}
if (process.env.NODE_ENV === 'development') {
// only use in development
arr.push(errorhandler());
}
// Serve static files
arr.push(express.static(opts.static));
// Logger
if (opts.logger) {
arr.push(logger('dev', {
skip: req => process.env.NODE_ENV === 'test' || req.path === '/favicon.ico'
}));
}
// No cache for IE
// https://support.microsoft.com/en-us/kb/234067
arr.push((req, res, next) => {
res.header('Cache-Control', 'no-cache');
res.header('Pragma', 'no-cache');
res.header('Expires', '-1');
next();
});
// Read-only
if (opts.readOnly) {
arr.push((req, res, next) => {
if (req.method === 'GET') {
next(); // Continue
} else {
res.sendStatus(403); // Forbidden
}
});
}
// Add middlewares
if (opts.bodyParser) {
arr.push(bodyParser);
}
return arr;
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
const express = require('express');
module.exports = {
create: () => express().set('json spaces', 2),
defaults: require('./defaults'),
router: require('./router'),
rewriter: require('./rewriter'),
bodyParser: require('./body-parser')
};
+73
View File
@@ -0,0 +1,73 @@
'use strict';
const nanoid = require('nanoid');
const pluralize = require('pluralize');
module.exports = {
getRemovable,
createId,
deepQuery
// Returns document ids that have unsatisfied relations
// Example: a comment that references a post that doesn't exist
};function getRemovable(db, opts) {
const _ = this;
const removable = [];
_.each(db, (coll, collName) => {
_.each(coll, doc => {
_.each(doc, (value, key) => {
if (new RegExp(`${opts.foreignKeySuffix}$`).test(key)) {
// Remove foreign key suffix and pluralize it
// Example postId -> posts
const refName = pluralize.plural(key.replace(new RegExp(`${opts.foreignKeySuffix}$`), ''));
// Test if table exists
if (db[refName]) {
// Test if references is defined in table
const ref = _.getById(db[refName], value);
if (_.isUndefined(ref)) {
removable.push({ name: collName, id: doc.id });
}
}
}
});
});
});
return removable;
}
// Return incremented id or uuid
// Used to override lodash-id's createId with utils.createId
function createId(coll) {
const _ = this;
const idProperty = _.__id();
if (_.isEmpty(coll)) {
return 1;
} else {
let id = _(coll).maxBy(idProperty)[idProperty];
// Increment integer id or generate string id
return _.isFinite(id) ? ++id : nanoid(7);
}
}
function deepQuery(value, q) {
const _ = this;
if (value && q) {
if (_.isArray(value)) {
for (let i = 0; i < value.length; i++) {
if (_.deepQuery(value[i], q)) {
return true;
}
}
} else if (_.isObject(value) && !_.isArray(value)) {
for (let k in value) {
if (_.deepQuery(value[k], q)) {
return true;
}
}
} else if (value.toString().toLowerCase().indexOf(q) !== -1) {
return true;
}
}
}
+18
View File
@@ -0,0 +1,18 @@
'use strict';
const express = require('express');
const rewrite = require('express-urlrewrite');
module.exports = routes => {
const router = express.Router();
router.get('/__rules', (req, res) => {
res.json(routes);
});
Object.keys(routes).forEach(key => {
router.use(rewrite(key, routes[key]));
});
return router;
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
const pause = require('connect-pause');
module.exports = function delay(req, res, next) {
// NOTE: for some reason unknown to me, if the default is 0, the tests seems to add 2 seconds
// NOTE: to each test, a default value of 1 does not seem to be effected by that issue
const _delay = !isNaN(parseFloat(req.query._delay)) ? parseFloat(req.query._delay) : 1;
delete req.query._delay;
pause(_delay)(req, res, next);
};
+12
View File
@@ -0,0 +1,12 @@
'use strict';
const url = require('url');
module.exports = function getFullURL(req) {
const root = url.format({
protocol: req.protocol,
host: req.get('host')
});
return `${root}${req.originalUrl}`;
};
+94
View File
@@ -0,0 +1,94 @@
'use strict';
const express = require('express');
const methodOverride = require('method-override');
const _ = require('lodash');
const lodashId = require('lodash-id');
const low = require('lowdb');
const fileAsync = require('lowdb/lib/storages/file-async');
const bodyParser = require('../body-parser');
const validateData = require('./validate-data');
const plural = require('./plural');
const nested = require('./nested');
const singular = require('./singular');
const mixins = require('../mixins');
module.exports = (source, opts = { foreignKeySuffix: 'Id' }) => {
// Create router
const router = express.Router();
// Add middlewares
router.use(methodOverride());
router.use(bodyParser);
// Create database
let db;
if (_.isObject(source)) {
db = low();
db.setState(source);
} else {
db = low(source, { storage: fileAsync });
}
validateData(db.getState());
// Add lodash-id methods to db
db._.mixin(lodashId);
// Add specific mixins
db._.mixin(mixins);
// Expose database
router.db = db;
// Expose render
router.render = (req, res) => {
res.jsonp(res.locals.data);
};
// GET /db
router.get('/db', (req, res) => {
res.jsonp(db.getState());
});
// Handle /:parent/:parentId/:resource
router.use(nested(opts));
// Create routes
db.forEach((value, key) => {
if (_.isPlainObject(value)) {
router.use(`/${key}`, singular(db, key));
return;
}
if (_.isArray(value)) {
router.use(`/${key}`, plural(db, key, opts));
return;
}
var sourceMessage = '';
if (!_.isObject(source)) {
sourceMessage = `in ${source}`;
}
const msg = `Type of "${key}" (${typeof value}) ${sourceMessage} is not supported. ` + `Use objects or arrays of objects.`;
throw new Error(msg);
}).value();
router.use((req, res) => {
if (!res.locals.data) {
res.status(404);
res.locals.data = {};
}
router.render(req, res);
});
router.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(err.stack);
});
return router;
};
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const express = require('express');
const pluralize = require('pluralize');
const delay = require('./delay');
module.exports = opts => {
const router = express.Router();
router.use(delay);
// Rewrite URL (/:resource/:id/:nested -> /:nested) and request query
function get(req, res, next) {
const prop = pluralize.singular(req.params.resource);
req.query[`${prop}${opts.foreignKeySuffix}`] = req.params.id;
req.url = `/${req.params.nested}`;
next();
}
// Rewrite URL (/:resource/:id/:nested -> /:nested) and request body
function post(req, res, next) {
const prop = pluralize.singular(req.params.resource);
req.body[`${prop}${opts.foreignKeySuffix}`] = req.params.id;
req.url = `/${req.params.nested}`;
next();
}
return router.get('/:resource/:id/:nested', get).post('/:resource/:id/:nested', post);
};
+273
View File
@@ -0,0 +1,273 @@
'use strict';
const express = require('express');
const _ = require('lodash');
const pluralize = require('pluralize');
const write = require('./write');
const getFullURL = require('./get-full-url');
const utils = require('../utils');
const delay = require('./delay');
module.exports = (db, name, opts) => {
// Create router
const router = express.Router();
router.use(delay);
// Embed function used in GET /name and GET /name/id
function embed(resource, e) {
e && [].concat(e).forEach(externalResource => {
if (db.get(externalResource).value) {
const query = {};
const singularResource = pluralize.singular(name);
query[`${singularResource}${opts.foreignKeySuffix}`] = resource.id;
resource[externalResource] = db.get(externalResource).filter(query).value();
}
});
}
// Expand function used in GET /name and GET /name/id
function expand(resource, e) {
e && [].concat(e).forEach(innerResource => {
const plural = pluralize(innerResource);
if (db.get(plural).value()) {
const prop = `${innerResource}${opts.foreignKeySuffix}`;
resource[innerResource] = db.get(plural).getById(resource[prop]).value();
}
});
}
// GET /name
// GET /name?q=
// GET /name?attr=&attr=
// GET /name?_end=&
// GET /name?_start=&_end=&
// GET /name?_embed=&_expand=
function list(req, res, next) {
// Resource chain
let chain = db.get(name);
// Remove q, _start, _end, ... from req.query to avoid filtering using those
// parameters
let q = req.query.q;
let _start = req.query._start;
let _end = req.query._end;
let _page = req.query._page;
let _sort = req.query._sort;
let _order = req.query._order;
let _limit = req.query._limit;
let _embed = req.query._embed;
let _expand = req.query._expand;
delete req.query.q;
delete req.query._start;
delete req.query._end;
delete req.query._sort;
delete req.query._order;
delete req.query._limit;
delete req.query._embed;
delete req.query._expand;
// Automatically delete query parameters that can't be found
// in the database
Object.keys(req.query).forEach(query => {
const arr = db.get(name).value();
for (let i in arr) {
if (_.has(arr[i], query) || query === 'callback' || query === '_' || /_lte$/.test(query) || /_gte$/.test(query) || /_ne$/.test(query) || /_like$/.test(query)) return;
}
delete req.query[query];
});
if (q) {
// Full-text search
if (Array.isArray(q)) {
q = q[0];
}
q = q.toLowerCase();
chain = chain.filter(obj => {
for (let key in obj) {
const value = obj[key];
if (db._.deepQuery(value, q)) {
return true;
}
}
});
}
Object.keys(req.query).forEach(key => {
// Don't take into account JSONP query parameters
// jQuery adds a '_' query parameter too
if (key !== 'callback' && key !== '_') {
// Always use an array, in case req.query is an array
const arr = [].concat(req.query[key]);
chain = chain.filter(element => {
return arr.map(function (value) {
const isDifferent = /_ne$/.test(key);
const isRange = /_lte$/.test(key) || /_gte$/.test(key);
const isLike = /_like$/.test(key);
const path = key.replace(/(_lte|_gte|_ne|_like)$/, '');
// get item value based on path
// i.e post.title -> 'foo'
const elementValue = _.get(element, path);
// Prevent toString() failing on undefined or null values
if (elementValue === undefined || elementValue === null) {
return;
}
if (isRange) {
const isLowerThan = /_gte$/.test(key);
return isLowerThan ? value <= elementValue : value >= elementValue;
} else if (isDifferent) {
return value !== elementValue.toString();
} else if (isLike) {
return new RegExp(value, 'i').test(elementValue.toString());
} else {
return value === elementValue.toString();
}
}).reduce((a, b) => a || b);
});
}
});
// Sort
if (_sort) {
const _sortSet = _sort.split(',');
const _orderSet = (_order || '').split(',').map(s => s.toLowerCase());
chain = chain.orderBy(_sortSet, _orderSet);
}
// Slice result
if (_end || _limit || _page) {
res.setHeader('X-Total-Count', chain.size());
res.setHeader('Access-Control-Expose-Headers', `X-Total-Count${_page ? ', Link' : ''}`);
}
if (_page) {
_page = parseInt(_page, 10);
_page = _page >= 1 ? _page : 1;
_limit = parseInt(_limit, 10) || 10;
const page = utils.getPage(chain.value(), _page, _limit);
const links = {};
const fullURL = getFullURL(req);
if (page.first) {
links.first = fullURL.replace(`page=${page.current}`, `page=${page.first}`);
}
if (page.prev) {
links.prev = fullURL.replace(`page=${page.current}`, `page=${page.prev}`);
}
if (page.next) {
links.next = fullURL.replace(`page=${page.current}`, `page=${page.next}`);
}
if (page.last) {
links.last = fullURL.replace(`page=${page.current}`, `page=${page.last}`);
}
res.links(links);
chain = _.chain(page.items);
} else if (_end) {
_start = parseInt(_start, 10) || 0;
_end = parseInt(_end, 10);
chain = chain.slice(_start, _end);
} else if (_limit) {
_start = parseInt(_start, 10) || 0;
_limit = parseInt(_limit, 10);
chain = chain.slice(_start, _start + _limit);
}
// embed and expand
chain = chain.cloneDeep().forEach(function (element) {
embed(element, _embed);
expand(element, _expand);
});
res.locals.data = chain.value();
next();
}
// GET /name/:id
// GET /name/:id?_embed=&_expand
function show(req, res, next) {
const _embed = req.query._embed;
const _expand = req.query._expand;
const resource = db.get(name).getById(req.params.id).value();
if (resource) {
// Clone resource to avoid making changes to the underlying object
const clone = _.cloneDeep(resource);
// Embed other resources based on resource id
// /posts/1?_embed=comments
embed(clone, _embed);
// Expand inner resources based on id
// /posts/1?_expand=user
expand(clone, _expand);
res.locals.data = clone;
}
next();
}
// POST /name
function create(req, res, next) {
const resource = db.get(name).insert(req.body).value();
res.setHeader('Access-Control-Expose-Headers', 'Location');
res.location(`${getFullURL(req)}/${resource.id}`);
res.status(201);
res.locals.data = resource;
next();
}
// PUT /name/:id
// PATCH /name/:id
function update(req, res, next) {
const id = req.params.id;
let chain = db.get(name);
chain = req.method === 'PATCH' ? chain.updateById(id, req.body) : chain.replaceById(id, req.body);
const resource = chain.value();
if (resource) {
res.locals.data = resource;
}
next();
}
// DELETE /name/:id
function destroy(req, res, next) {
const resource = db.get(name).removeById(req.params.id).value();
// Remove dependents documents
const removable = db._.getRemovable(db.getState(), opts);
removable.forEach(item => {
db.get(item.name).removeById(item.id).value();
});
if (resource) {
res.locals.data = {};
}
next();
}
const w = write(db);
router.route('/').get(list).post(create, w);
router.route('/:id').get(show).put(update, w).patch(update, w).delete(destroy, w);
return router;
};
+44
View File
@@ -0,0 +1,44 @@
'use strict';
const express = require('express');
const write = require('./write');
const getFullURL = require('./get-full-url');
const delay = require('./delay');
module.exports = (db, name) => {
const router = express.Router();
router.use(delay);
function show(req, res, next) {
res.locals.data = db.get(name).value();
next();
}
function create(req, res, next) {
db.set(name, req.body).value();
res.locals.data = db.get(name).value();
res.setHeader('Access-Control-Expose-Headers', 'Location');
res.location(`${getFullURL(req)}`);
res.status(201);
next();
}
function update(req, res, next) {
if (req.method === 'PUT') {
db.set(name, req.body).value();
} else {
db.get(name).assign(req.body).value();
}
res.locals.data = db.get(name).value();
next();
}
const w = write(db);
router.route('/').get(show).post(create, w).put(update, w).patch(update, w);
return router;
};
+18
View File
@@ -0,0 +1,18 @@
'use strict';
const _ = require('lodash');
function validateKey(key) {
if (key.indexOf('/') !== -1) {
const msg = [`Oops, found / character in database property '${key}'.`, '', "/ aren't supported, if you want to tweak default routes, see", 'https://github.com/typicode/json-server/#add-custom-routes'].join('\n');
throw new Error(msg);
}
}
module.exports = obj => {
if (_.isPlainObject(obj)) {
Object.keys(obj).forEach(validateKey);
} else {
throw new Error(`Data must be an object. Found ${typeof obj}.` + 'See https://github.com/typicode/json-server for example.');
}
};
+8
View File
@@ -0,0 +1,8 @@
"use strict";
module.exports = function write(db) {
return (req, res, next) => {
db.write();
next();
};
};
+32
View File
@@ -0,0 +1,32 @@
"use strict";
module.exports = {
getPage
};
function getPage(array, page, perPage) {
var obj = {};
var start = (page - 1) * perPage;
var end = page * perPage;
obj.items = array.slice(start, end);
if (obj.items.length === 0) {
return obj;
}
if (page > 1) {
obj.prev = page - 1;
}
if (end < array.length) {
obj.next = page + 1;
}
if (obj.items.length !== array.length) {
obj.current = page;
obj.first = 1;
obj.last = Math.ceil(array.length / perPage);
}
return obj;
}