Skip to content

Instantly share code, notes, and snippets.

@par6n
Created March 22, 2020 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save par6n/a59477826c357cced6693ba751ccfb20 to your computer and use it in GitHub Desktop.
Save par6n/a59477826c357cced6693ba751ccfb20 to your computer and use it in GitHub Desktop.
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