Skip to content

Instantly share code, notes, and snippets.

@marcusradell
Last active November 8, 2019 10:22
Show Gist options
  • Save marcusradell/69af5a883457a7b0c0fee8a73a7313dc to your computer and use it in GitHub Desktop.
Save marcusradell/69af5a883457a7b0c0fee8a73a7313dc to your computer and use it in GitHub Desktop.
import { Router } from 'express';
import { printCurls } from './curls';
import { modelFactory } from './model';
import { ExceptionResult, FailureResult } from '../../types';
import { CodeCaseAction } from './types';
import * as t from 'io-ts';
import { pipe } from 'fp-ts/lib/pipeable';
import { fold, either } from 'fp-ts/lib/Either';
import { Collection } from 'mongodb';
export const codeCasesFactory = (
router: Router,
collection: Collection<unknown>
) => {
if (process.env.PRINT_CODE_CASE_CURLS) {
printCurls();
}
const model = modelFactory(collection);
router.post('/api/code-cases/', (req, res) => {
const rawAction: unknown = req.body;
const onFailure = (errors: t.Errors): string => {
const result: FailureResult = {
status: 'failed',
type: 'validation_failed'
};
// TODO: Only have one res.send
res.send(result);
return `Action failed. ${errors.map(error =>
error.context.map(({ key }) => key).join('.')
)}`;
};
const onSuccess = () => `Action succeeded.`;
const rawToken = req.headers['x-access-token'];
pipe(
either.map(CodeCaseAction.decode(rawAction), async action => {
const result = await model
.handleAction(rawToken, action)
.catch(error => {
const result: ExceptionResult = {
status: 'exceptioned',
type: 'unexpected_error',
stack: error.stack || new Error().stack
};
return result;
});
// TODO: Only have one res.send
res.send(result);
}),
// TODO: How should we fold?
fold(onFailure, onSuccess)
);
});
return {
model
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment