UNPKG

@chubbyts/chubbyts-api

Version:

[![CI](https://github.com/chubbyts/chubbyts-api/workflows/CI/badge.svg?branch=master)](https://github.com/chubbyts/chubbyts-api/actions?query=workflow%3ACI) [![Coverage Status](https://coveralls.io/repos/github/chubbyts/chubbyts-api/badge.svg?branch=maste

29 lines (28 loc) 1.54 kB
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, inputModelSchema, persistModel, responseFactory, enrichedModelSchema, 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 = inputModelSchema.safeParse(rest); if (!modelRequestResult.success) { throw createBadRequest({ invalidParameters: zodToInvalidParameters(modelRequestResult.error) }); } return stringifyResponseBody(request, responseFactory(200), encoder, valueToData(enrichedModelSchema.parse(await enrichModel(await persistModel({ id: model.id, createdAt: model.createdAt, updatedAt: new Date(), ...modelRequestResult.data, }), { request, })))); }; };