From 46050422027fab1bcf5810368dcbdcb65bd3571e Mon Sep 17 00:00:00 2001 From: Swain Molster Date: Mon, 22 Aug 2022 09:35:57 -0400 Subject: [PATCH] update docs and improve tests --- README.md | 13 +++++++++++ src/integration.koa.test.ts | 45 ++++++++++++++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 32bb216..e2986fa 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,19 @@ const server = new Koa() .listen(); ``` +By default, `implementSchema` will perform input validation on all of your routes, using the defined `Request` schemas. +To customize this input validation, specify a `parse` function: + +```typescript +implementSchema(Schema, { + // ... + parse: (ctx, { endpoint, schema, data }) => { + // Validate `data` against the `schema`. + // If the data is valid, return it, otherwise throw. + }, +}); +``` + ### Axios Client Generation Projects that want to safely consume a service that uses `one-schema` can perform introspection using `fetch-remote-schema`. diff --git a/src/integration.koa.test.ts b/src/integration.koa.test.ts index 0a1a3dd..37fedcd 100644 --- a/src/integration.koa.test.ts +++ b/src/integration.koa.test.ts @@ -257,7 +257,7 @@ test('introspection', async () => { ); }); -test('default parsing for POST', async () => { +test('default parsing for POST fails invalid data', async () => { await executeTest( { parse: undefined, @@ -266,7 +266,7 @@ test('default parsing for POST', async () => { }, }, async (client) => { - const result = await client.post('/posts'); + const result = await client.post('/posts', {}); expect(result).toMatchObject({ status: 400, @@ -276,7 +276,28 @@ test('default parsing for POST', async () => { ); }); -test('default parsing for GET', async () => { +test('default parsing for POST allows valid data', async () => { + await executeTest( + { + parse: undefined, + implementation: { + 'POST /posts': (ctx) => ctx.request.body, + }, + }, + async (client) => { + const result = await client.post('/posts', { + id: 'some-id', + message: 'some-message', + }); + + expect(result).toMatchObject({ + status: 200, + }); + }, + ); +}); + +test('default parsing for GET fails invalid data', async () => { await executeTest( { parse: undefined, @@ -296,3 +317,21 @@ test('default parsing for GET', async () => { }, ); }); + +test('default parsing for GET allows valid data', async () => { + await executeTest( + { + parse: undefined, + implementation: { + 'GET /posts': (ctx) => ctx.request.body, + }, + }, + async (client) => { + const result = await client.get('/posts?input=something'); + + expect(result).toMatchObject({ + status: 200, + }); + }, + ); +});