fix api global options.

This commit is contained in:
Ahmed Bouhuolia
2020-04-15 20:13:55 +02:00
parent d02517e66d
commit ff0a26a790
7 changed files with 281 additions and 25 deletions

View File

@@ -0,0 +1,38 @@
export default {
organization: [
{
key: 'name',
type: 'string',
},
{
key: 'base_currency',
type: 'string',
},
{
key: 'industry',
type: 'string',
},
{
key: 'location',
type: 'string',
},
{
key: 'fiscal_year',
type: 'string',
},
{
key: 'language',
type: 'string',
},
{
key: 'time_zone',
type: 'string',
},
{
key: 'date_format',
type: 'string',
},
],
};

View File

@@ -1,7 +1,9 @@
import express from 'express';
import { body, query, validationResult } from 'express-validator';
import { pick } from 'lodash';
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
import Option from '@/models/Option';
import jwtAuth from '@/http/middleware/jwtAuth';
export default {
/**
@@ -10,13 +12,15 @@ export default {
router() {
const router = express.Router();
router.use(jwtAuth);
router.post('/',
this.saveOptions.validation,
asyncMiddleware(this.saveOptions.handler));
router.get('/',
this.getOptions.validation,
asyncMiddleware(this.getSettings));
asyncMiddleware(this.getOptions.handler));
return router;
},
@@ -26,7 +30,7 @@ export default {
*/
saveOptions: {
validation: [
body('options').isArray(),
body('options').isArray({ min: 1 }),
body('options.*.key').exists(),
body('options.*.value').exists(),
body('options.*.group').exists(),
@@ -42,12 +46,25 @@ export default {
const form = { ...req.body };
const optionsCollections = await Option.query();
const errorReasons = [];
const notDefinedOptions = Option.validateDefined(form.options);
if (notDefinedOptions.length) {
errorReasons.push({
type: 'OPTIONS.KEY.NOT.DEFINED',
code: 200,
keys: notDefinedOptions.map(o => ({ ...pick(o, ['key', 'group']) })),
});
}
if (errorReasons.length) {
return res.status(400).send({ errors: errorReasons });
}
form.options.forEach((option) => {
optionsCollections.setMeta(option.key, option.value, option.group);
optionsCollections.setMeta({ ...option });
});
await optionsCollections.saveMeta();
return res.status(200).send();
return res.status(200).send({ options: form });
},
},
@@ -57,6 +74,7 @@ export default {
getOptions: {
validation: [
query('key').optional(),
query('group').optional(),
],
async handler(req, res) {
const validationErrors = validationResult(req);
@@ -66,9 +84,17 @@ export default {
code: 'VALIDATION_ERROR', ...validationErrors,
});
}
const options = await Option.query();
return res.status(200).sends({ options });
const filter = { ...req.query };
const options = await Option.query().onBuild((builder) => {
if (filter.key) {
builder.where('key', filter.key);
}
if (filter.group) {
builder.where('group', filter.group);
}
});
return res.status(200).send({ options: options.metadata });
},
},
};

View File

@@ -1,5 +1,8 @@
export default class MetableCollection {
/**
* Constructor method.
*/
constructor() {
this.metadata = [];
this.KEY_COLUMN = 'key';
@@ -21,13 +24,29 @@ export default class MetableCollection {
this.model = model;
}
/**
* Sets a extra columns.
* @param {Array} columns -
*/
setExtraColumns(columns) {
this.extraColumns = columns;
}
/**
* Find the given metadata key.
* @param {String} key -
* @return {object} - Metadata object.
*/
findMeta(key) {
return this.allMetadata().find((meta) => meta.key === key);
findMeta(payload) {
const { key, extraColumns } = this.parsePayload(payload);
return this.allMetadata().find((meta) => {
const isSameKey = meta.key === key;
const sameExtraColumns = this.extraColumns.some((extraColumn) => {
return !extraColumns || (extraColumns[extraColumn] === meta[extraColumn]);
});
return isSameKey && sameExtraColumns;
});
}
/**
@@ -42,8 +61,8 @@ export default class MetableCollection {
* @param {String} key -
* @param {Mixied} defaultValue -
*/
getMeta(key, defaultValue) {
const metadata = this.findMeta(key);
getMeta(payload, defaultValue) {
const metadata = this.findMeta(payload);
return metadata ? metadata.value : defaultValue || false;
}
@@ -79,7 +98,7 @@ export default class MetableCollection {
* @param {String} key -
* @param {String} value -
*/
setMeta(key, value, payload) {
setMeta(payload, ...args) {
if (Array.isArray(key)) {
const metadata = key;
@@ -88,18 +107,23 @@ export default class MetableCollection {
});
return;
}
const metadata = this.findMeta(key);
const { key, value, ...extraColumns } = this.parsePayload(payload, args[0]);
const metadata = this.findMeta(payload);
if (metadata) {
metadata.value = value;
metadata.markAsUpdated = true;
} else {
this.metadata.push({
value, key, ...payload, markAsInserted: true,
value, key, ...extraColumns, markAsInserted: true,
});
}
}
parsePayload(payload, value) {
return typeof payload !== 'object' ? { key: payload, value } : { ...payload };
}
/**
* Saved the modified/deleted and inserted metadata.
*/
@@ -111,7 +135,7 @@ export default class MetableCollection {
if (deleted.length > 0) {
deleted.forEach((meta) => {
const deleteOper = this.model.query().beforeRun((query, result) => {
const deleteOper = this.model.query().onBuild((query, result) => {
this.extraQuery(query, meta);
return result;
}).delete();

View File

@@ -1,6 +1,7 @@
import { mixin } from 'objection';
import BaseModel from '@/models/Model';
import MetableCollection from '@/lib/Metable/MetableCollection';
import definedOptions from '@/data/options';
export default class Option extends mixin(BaseModel, [mixin]) {
/**
@@ -18,6 +19,7 @@ export default class Option extends mixin(BaseModel, [mixin]) {
return super.query(...args).runAfter((result) => {
if (result instanceof MetableCollection) {
result.setModel(Option);
result.setExtraColumns(['group']);
}
return result;
});
@@ -26,4 +28,17 @@ export default class Option extends mixin(BaseModel, [mixin]) {
static get collection() {
return MetableCollection;
}
static validateDefined(options) {
const notDefined = [];
options.forEach((option) => {
if (!definedOptions[option.group]) {
notDefined.push(option);
} else if (!definedOptions[option.group].some((o) => o.key === option.key)) {
notDefined.push(option);
}
});
return notDefined;
}
}