From a2777a263a1c90596e0d8e0e8e5ce43ff2bc83e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Mon, 2 Sep 2019 11:28:35 +0200 Subject: [PATCH] feat(rest-crud): add "replaceById" endpoint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Miroslav Bajtoš --- .../default-model-crud-rest.acceptance.ts | 35 +++++++++++++++++++ .../rest-crud/src/crud-rest.controller.ts | 13 +++++++ 2 files changed, 48 insertions(+) diff --git a/packages/rest-crud/src/__tests__/acceptance/default-model-crud-rest.acceptance.ts b/packages/rest-crud/src/__tests__/acceptance/default-model-crud-rest.acceptance.ts index 3a363aabf0a6..3167ff0a746b 100644 --- a/packages/rest-crud/src/__tests__/acceptance/default-model-crud-rest.acceptance.ts +++ b/packages/rest-crud/src/__tests__/acceptance/default-model-crud-rest.acceptance.ts @@ -213,6 +213,41 @@ describe('CrudRestController for a simple Product model', () => { }); }); + describe('replaceById', () => { + beforeEach(seedData); + + it('replaces model with the given id', async () => { + const newData = Object.assign({}, pen.toJSON(), PATCH_DATA); + await client + .put(`/products/${pen.id}`) + .send(newData) + .expect(204); + + const stored = await repo.find(); + expect(toJSON(stored)).to.deepEqual([ + {...newData}, + {...toJSON(pencil) /* pencil was not modified */}, + ]); + }); + + // TODO(bajtos) to fully verify this functionality, we should create + // a new test suite that will configure a PK with a different name + // and type, e.g. `pk: string` instead of `id: number`. + it('uses correct schema for the id parameter', async () => { + const spec = app.restServer.getApiSpec(); + const findByIdOp = spec.paths['/products/{id}']['patch']; + expect(findByIdOp).to.containDeep({ + parameters: [ + { + name: 'id', + in: 'path', + schema: {type: 'number'}, + }, + ], + }); + }); + }); + describe('deleteById', () => { beforeEach(seedData); diff --git a/packages/rest-crud/src/crud-rest.controller.ts b/packages/rest-crud/src/crud-rest.controller.ts index cf83f1e5d3ab..4ad0dd34105c 100644 --- a/packages/rest-crud/src/crud-rest.controller.ts +++ b/packages/rest-crud/src/crud-rest.controller.ts @@ -27,6 +27,7 @@ import { ParameterObject, patch, post, + put, requestBody, ResponsesObject, SchemaObject, @@ -231,6 +232,18 @@ export function defineCrudRestController< ); } + @put('/{id}', { + responses: { + '204': {description: `${modelName} was updated`}, + }, + }) + async replaceById( + @param(idPathParam) id: IdType, + @body(modelCtor) data: T, + ): Promise { + await this.repository.replaceById(id, data); + } + @del('/{id}', { responses: { '204': {description: `${modelName} was deleted`},