Skip to content

Instantly share code, notes, and snippets.

@par6n
Created Mar 22, 2020
Embed
What would you like to do?
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