Skip to content

Commit

Permalink
Merge pull request #11 from hckrnews/feature/phase1
Browse files Browse the repository at this point in the history
Mock undefined controllers
  • Loading branch information
w3nl authored Jun 22, 2023
2 parents 1a16712 + 2c324b6 commit e5241de
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 3 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@hckrnews/openapi-server",
"description": "OpenAPI Server",
"version": "0.1.7",
"version": "0.1.8",
"author": {
"name": "Pieter Wigboldus",
"url": "https://hckr.news/"
Expand Down
31 changes: 31 additions & 0 deletions src/__fixtures__/spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,37 @@
}
]
}
},
"/v1/user": {
"get": {
"operationId": "getUser",
"summary": "Get all user record",
"description": "Get the user record from the database.",
"parameters": [],
"responses": {
"200": {
"description": "",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/user"
}
}
}
},
"401": {
"description": "Unauthorized"
}
},
"tags": [
"Example"
],
"security": [
{
"apiKey": []
}
]
}
}
},
"info": {
Expand Down
10 changes: 10 additions & 0 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ export const setupRouter = ({ env, openAPISpecification, controllers }) => {
})

operationIds({ specification: openAPISpecification }).forEach((operationId) => {
if (!Object.hasOwn(controllers, operationId)) {
return
}
api.register(
operationId,
makeExpressCallback({
Expand All @@ -36,6 +39,13 @@ export const setupRouter = ({ env, openAPISpecification, controllers }) => {
)
})

api.register('notImplemented', (context, request, response) => {
const { mock } = context.api.mockResponseForOperation(
context.operation.operationId
)
return mock
})

api.registerSecurityHandler(
'apiKey',
(context) => context.request.headers['x-api-key'] === secret
Expand Down
11 changes: 11 additions & 0 deletions src/server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,17 @@ test('Test the server', async (t) => {
assert.deepEqual(response.body, exampleResponse)
})

await t.test('It should return the mocked user, because we don\' have a controller yet', async () => {
const response = await request
.get('/v1/user')
.set('x-api-key', envExample.SECRET)

assert.strictEqual(response.status, 200)
assert.deepEqual(response.body, {
name: 'Pieter'
})
})

await t.test('It should catch error\'s', async () => {
const response = await request
.get('/v1/users')
Expand Down

0 comments on commit e5241de

Please sign in to comment.