Skip to content

Commit

Permalink
Merge pull request #17 from lifeomic/allow-customizing-error
Browse files Browse the repository at this point in the history
feat: allow customizing success status codes
  • Loading branch information
swain authored May 31, 2022
2 parents d219c72 + 19320c7 commit 8da04f2
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
56 changes: 56 additions & 0 deletions src/koa.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import axios from 'axios';
import Koa = require('koa');
import bodyParser = require('koa-bodyparser');
import Router = require('koa-router');
import { implementSchema } from '.';
import { withAssumptions } from './meta-schema';
Expand Down Expand Up @@ -25,3 +28,56 @@ test('using unsupported methods throws immediately', () => {
);
}).toThrowError('Unsupported method detected: OPTIONS /post');
});

test('setting a 200-level response code overrides the response', async () => {
const router = new Router();
implementSchema(
withAssumptions({
Endpoints: {
'DELETE /post/:id': {
Name: 'deletePost',
Response: {},
},
'POST /posts': {
Name: 'createPost',
Response: {},
},
},
}),
{
on: router,
parse: () => null as any,
implementation: {
'DELETE /post/:id': (ctx) => {
ctx.response.status = 204;
return {};
},
'POST /posts': (ctx) => {
ctx.response.status = 301;
return {};
},
},
},
);

const server = new Koa()
.use(bodyParser())
.use(router.routes())
.use(router.allowedMethods())
.listen();

const { port } = server.address() as any;

const client = axios.create({
baseURL: `http://localhost:${port}`,
validateStatus: () => true,
});

const deleteRes = await client.delete('/post/bogus');
expect(deleteRes.status).toStrictEqual(204);

const createRes = await client.post('/posts');
expect(createRes.status).toStrictEqual(200);

server.close();
});
6 changes: 5 additions & 1 deletion src/koa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,11 @@ export const implementSchema = <State, Context, Schema extends OneSchema<any>>(

// 3. Return the result and call the next middleware.
ctx.response.body = response;
ctx.response.status = 200;
// If the response status is already set to a 200-level code, don't override it.
// This is the mechanism for allowing consumers to customize response codes.
if (ctx.response.status < 200 || ctx.response.status >= 300) {
ctx.response.status = 200;
}
return next();
};

Expand Down

0 comments on commit 8da04f2

Please sign in to comment.