|
const Bluebird = require('[email protected]') |
|
const lodash = require('[email protected]') |
|
|
|
/** |
|
* storage is an Object with properties as Array models: |
|
* storage: { |
|
* modelA: [{id: 1, name: 'example'}], |
|
* modelB: [{id: 1, color: 'red'}] |
|
* } |
|
*/ |
|
const getStorage = (ctx) => Bluebird.fromCallback(cb => { |
|
ctx.storage.get(cb) |
|
}) |
|
|
|
const getObjectStorage = (ctx) => getStorage(ctx) |
|
.then(storage => (typeof storage === 'object') ? storage : {}) |
|
|
|
const setStorage = (ctx, data, force) => Bluebird.fromCallback(cb => { |
|
ctx.storage.set(data, {force}, cb) |
|
}) |
|
|
|
const getModels = (ctx, modelName) => Bluebird.try(() => { |
|
if (!modelName) { |
|
throw new Error('modelName not provided') |
|
} |
|
return getObjectStorage(ctx).then(storage => { |
|
if (!Array.isArray(storage[modelName])) { |
|
storage[modelName] = [] |
|
} |
|
return storage[modelName] |
|
}) |
|
}) |
|
|
|
const filterModel = (ctx, modelName, props) => |
|
getModels(ctx, modelName).then(models => lodash.filter(models, props)) |
|
|
|
const findModel = (ctx, modelName, props) => |
|
getModels(ctx, modelName).then(models => lodash.find(models, props)) |
|
|
|
const saveModel = (ctx, modelName, props) => Bluebird.try(() => { |
|
if (!modelName) { |
|
throw new Error('modelName not provided') |
|
} |
|
return getObjectStorage(ctx).then(storage => { |
|
if (!storage[modelName]) { |
|
storage[modelName] = [] |
|
} |
|
storage[modelName].push(props) |
|
return setStorage(ctx, storage) |
|
}) |
|
}) |
|
|
|
const main = (ctx) => Bluebird.try(() => { |
|
const action = ctx.query.action |
|
|
|
console.log(`Action: ${action}`) |
|
console.log('Body: %j', ctx.body) |
|
|
|
switch (action) { |
|
case 'get_storage': { |
|
return getStorage(ctx) |
|
} |
|
case 'get_models': { |
|
return getModels(ctx, ctx.body.modelName) |
|
} |
|
case 'save_model': { |
|
return saveModel(ctx, ctx.body.modelName, ctx.body.properties) |
|
} |
|
case 'filter_model': { |
|
return filterModel(ctx, ctx.body.modelName, ctx.body.properties) |
|
} |
|
case 'find_model': { |
|
return findModel(ctx, ctx.body.modelName, ctx.body.properties) |
|
} |
|
case 'delete_all': { |
|
return setStorage(ctx, {}, 1) |
|
} |
|
default: { |
|
throw new Error('Action not allowed') |
|
} |
|
} |
|
}) |
|
|
|
module.exports = (ctx, cb) => main(ctx) |
|
.then(resp => { |
|
console.log('Response will be:', resp) |
|
cb(null, resp) |
|
}) |
|
.catch(err => { |
|
console.error('Response error') |
|
console.error(err) |
|
cb(err.message, null) |
|
}) |