2020-11-05 18:58:23 +02:00
|
|
|
import { Request, RequestMethod } from '../Api';
|
|
|
|
import defaultSaveOptions from './defaultSaveOptions';
|
|
|
|
import { ErrorMethodNotAllowed, ErrorNotFound } from './errors';
|
|
|
|
import paginatedResults from './paginatedResults';
|
|
|
|
import readonlyProperties from './readonlyProperties';
|
|
|
|
import requestFields from './requestFields';
|
2021-01-22 19:41:11 +02:00
|
|
|
import BaseItem from '../../../models/BaseItem';
|
2020-11-05 18:58:23 +02:00
|
|
|
|
2023-10-06 16:03:32 +02:00
|
|
|
export default async function(modelType: number, request: Request, id: string = null, link: string = null, defaultFields: string[] = null) {
|
2020-11-05 18:58:23 +02:00
|
|
|
if (link) throw new ErrorNotFound(); // Default action doesn't support links at all for now
|
|
|
|
|
|
|
|
const ModelClass = BaseItem.getClassByItemType(modelType);
|
|
|
|
|
2020-11-12 21:13:28 +02:00
|
|
|
const getOneModel = async (options: any = null) => {
|
2020-11-05 18:58:23 +02:00
|
|
|
const model = await ModelClass.load(id, options || {});
|
|
|
|
if (!model) throw new ErrorNotFound();
|
|
|
|
return model;
|
|
|
|
};
|
|
|
|
|
|
|
|
if (request.method === 'GET') {
|
|
|
|
if (id) {
|
|
|
|
return getOneModel({
|
2023-10-06 16:03:32 +02:00
|
|
|
fields: requestFields(request, modelType, defaultFields),
|
2020-11-05 18:58:23 +02:00
|
|
|
});
|
|
|
|
} else {
|
2023-10-06 16:03:32 +02:00
|
|
|
return paginatedResults(modelType, request, null, defaultFields);
|
2020-11-05 18:58:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (request.method === 'PUT' && id) {
|
|
|
|
const model = await getOneModel();
|
2023-06-01 13:02:36 +02:00
|
|
|
const newModel = { ...model, ...request.bodyJson(readonlyProperties('PUT')) };
|
2020-11-05 18:58:23 +02:00
|
|
|
return ModelClass.save(newModel, { userSideValidation: true });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (request.method === 'DELETE' && id) {
|
|
|
|
const model = await getOneModel();
|
|
|
|
await ModelClass.delete(model.id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (request.method === RequestMethod.POST) {
|
|
|
|
const props = readonlyProperties('POST');
|
|
|
|
const idIdx = props.indexOf('id');
|
|
|
|
if (idIdx >= 0) props.splice(idIdx, 1);
|
|
|
|
const model = request.bodyJson(props);
|
|
|
|
return ModelClass.save(model, defaultSaveOptions('POST', model.id));
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new ErrorMethodNotAllowed();
|
|
|
|
}
|