Notes/src/etapi/attributes.js

78 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-01-07 19:33:59 +01:00
const becca = require("../becca/becca");
2022-01-10 17:09:20 +01:00
const eu = require("./etapi_utils");
2022-01-07 19:33:59 +01:00
const mappers = require("./mappers");
const attributeService = require("../services/attributes");
2022-01-12 19:32:23 +01:00
const v = require("./validators");
2022-01-07 19:33:59 +01:00
function register(router) {
2022-01-10 17:09:20 +01:00
eu.route(router, 'get', '/etapi/attributes/:attributeId', (req, res, next) => {
const attribute = eu.getAndCheckAttribute(req.params.attributeId);
2022-01-07 19:33:59 +01:00
res.json(mappers.mapAttributeToPojo(attribute));
});
2022-01-12 19:32:23 +01:00
const ALLOWED_PROPERTIES_FOR_CREATE_ATTRIBUTE = {
'attributeId': [v.mandatory, v.notNull, v.isValidEntityId],
'noteId': [v.mandatory, v.notNull, v.isNoteId],
'type': [v.mandatory, v.notNull, v.isAttributeType],
'name': [v.mandatory, v.notNull, v.isString],
'value': [v.notNull, v.isString],
'isInheritable': [v.notNull, v.isBoolean],
'position': [v.notNull, v.isInteger]
2022-01-12 19:32:23 +01:00
};
2022-01-10 17:09:20 +01:00
eu.route(router, 'post' ,'/etapi/attributes', (req, res, next) => {
2022-01-12 19:32:23 +01:00
if (req.body.type === 'relation') {
eu.getAndCheckNote(req.body.value);
2022-01-07 19:33:59 +01:00
}
2022-01-12 19:32:23 +01:00
const params = {};
2022-01-12 19:32:23 +01:00
eu.validateAndPatch(params, req.body, ALLOWED_PROPERTIES_FOR_CREATE_ATTRIBUTE);
2022-01-07 19:33:59 +01:00
try {
const attr = attributeService.createAttribute(params);
res.status(201).json(mappers.mapAttributeToPojo(attr));
2022-01-07 19:33:59 +01:00
}
catch (e) {
2022-01-12 19:32:23 +01:00
throw new eu.EtapiError(500, eu.GENERIC_CODE, e.message);
2022-01-07 19:33:59 +01:00
}
});
const ALLOWED_PROPERTIES_FOR_PATCH = {
'value': [v.notNull, v.isString],
'position': [v.notNull, v.isInteger]
2022-01-07 19:33:59 +01:00
};
2022-01-10 17:09:20 +01:00
eu.route(router, 'patch' ,'/etapi/attributes/:attributeId', (req, res, next) => {
const attribute = eu.getAndCheckAttribute(req.params.attributeId);
2022-01-07 19:33:59 +01:00
2022-01-12 19:32:23 +01:00
if (attribute.type === 'relation') {
eu.getAndCheckNote(req.body.value);
}
2022-01-10 17:09:20 +01:00
eu.validateAndPatch(attribute, req.body, ALLOWED_PROPERTIES_FOR_PATCH);
2022-01-12 19:32:23 +01:00
attribute.save();
2022-01-07 19:33:59 +01:00
res.json(mappers.mapAttributeToPojo(attribute));
});
2022-01-10 17:09:20 +01:00
eu.route(router, 'delete' ,'/etapi/attributes/:attributeId', (req, res, next) => {
2022-01-07 19:33:59 +01:00
const attribute = becca.getAttribute(req.params.attributeId);
2022-01-08 12:01:54 +01:00
if (!attribute || attribute.isDeleted) {
2022-01-07 19:33:59 +01:00
return res.sendStatus(204);
}
attribute.markAsDeleted();
res.sendStatus(204);
});
}
module.exports = {
register
2022-01-08 12:01:54 +01:00
};