@chubbyts/chubbyts-api
Version:
[](https://github.com/chubbyts/chubbyts-api/actions?query=workflow%3ACI) [ • 1.46 kB
JavaScript
import { createBadRequest, createNotFound } from '@chubbyts/chubbyts-http-error/dist/http-error';
import { z } from 'zod';
import { parseRequestBody } from '../request.js';
import { stringifyResponseBody, valueToData } from '../response.js';
import { zodToInvalidParameters } from '../zod-to-invalid-parameters.js';
const attributesSchema = z.object({ id: z.string() });
export const createUpdateHandler = (findModelById, decoder, modelRequestSchema, persistModel, responseFactory, modelResponseSchema, encoder, enrichModel = async (model) => model) => {
return async (request) => {
const id = attributesSchema.parse(request.attributes).id;
const model = await findModelById(id);
if (!model) {
throw createNotFound({ detail: `There is no entry with id "${id}"` });
}
const { id: _, createdAt: __, updatedAt: ___, _embedded: ____, _links: _____, ...rest } = (await parseRequestBody(decoder, request));
const modelRequestResult = modelRequestSchema.safeParse(rest);
if (!modelRequestResult.success) {
throw createBadRequest({ invalidParameters: zodToInvalidParameters(modelRequestResult.error) });
}
return stringifyResponseBody(request, responseFactory(200), encoder, modelResponseSchema.parse(valueToData(await enrichModel(await persistModel({ ...model, updatedAt: new Date(), ...modelRequestResult.data }), {
request,
}))));
};
};