Created
March 22, 2020 20:25
-
-
Save par6n/a59477826c357cced6693ba751ccfb20 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fastify from 'fastify'; | |
import { ServerResponse } from 'http'; | |
const S = require('sanctuary'); | |
const healthCheckRoutes = (fastify: fastify.FastifyInstance) => { | |
fastify.get( | |
'/ping', | |
{ | |
schema: { | |
response: { | |
200: { | |
type: 'object', | |
properties: { | |
ok: { | |
type: 'boolean', | |
}, | |
}, | |
}, | |
}, | |
}, | |
}, | |
async () => { | |
return { ok: true }; | |
}, | |
); | |
const validateHeaders = request => { | |
request.log.info(request.headers, 'headers'); | |
if (!request.headers['x-open-sesame']) { | |
return S.Left({ err: 'Unauthorized', status: 401 }); | |
} | |
return S.Right(request); | |
}; | |
const greet = (request: fastify.FastifyRequest) => { | |
return S.Right({ | |
ok: true, | |
message: `Hello, ${request.query.name || 'world'}!`, | |
}); | |
}; | |
const respond = (reply: fastify.FastifyReply<ServerResponse>) => what => { | |
if (what.value.status) { | |
reply.code(what.value.status); | |
} | |
if (S.isLeft(what)) { | |
return { ok: false, err: what.value.err }; | |
} else { | |
return what.value; | |
} | |
}; | |
fastify.get( | |
'/protected', | |
{ | |
schema: { | |
headers: { | |
type: 'object', | |
properties: { | |
'x-open-sesame': { type: 'boolean' }, | |
}, | |
}, | |
querystring: { | |
type: 'object', | |
properties: { | |
name: { type: 'string' }, | |
}, | |
}, | |
response: { | |
200: { | |
type: 'object', | |
properties: { | |
ok: { | |
type: 'boolean', | |
}, | |
err: { | |
type: 'string', | |
}, | |
message: { | |
type: 'string', | |
}, | |
}, | |
}, | |
}, | |
}, | |
}, | |
async ( | |
request: fastify.FastifyRequest, | |
reply: fastify.FastifyReply<ServerResponse>, | |
) => { | |
// return S.compose(respond(reply))(greet)(validateHeaders)(request); | |
return S.pipe([validateHeaders, S.chain(greet), respond(reply)])(request); | |
}, | |
); | |
}; | |
export default healthCheckRoutes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment