Created
August 2, 2017 09:24
-
-
Save ArturAralin/a49e8804b7fb4f6b2c8e18b949af99b3 to your computer and use it in GitHub Desktop.
This file contains 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 { Request, Response, Errback, NextFunction } from 'express'; | |
import { pick, bind, assoc, defaultTo } from 'ramda'; | |
import AppError from '../error-default'; | |
import { createLogger } from '../logger'; | |
import UnexpectedError from '../../lib/errors/unexpected'; | |
const DEFAULT_STATUS = 200; | |
const logger = createLogger('api-endpoint'); | |
function endpointFn(res: Response, data: object, params: App.EndpointParams = {}): void { | |
const { status } = params; | |
logger.debug(data as any); | |
res | |
.status(status || DEFAULT_STATUS) | |
.json({ data }); | |
} | |
export const errorEndpoint = (err: AppError, req: Request, res: App.Endpoint, next: NextFunction): void => { | |
let error = err; | |
if (!err.code && !err.status) { | |
const stack = (err as any).stack; | |
error = new UnexpectedError(stack); | |
} | |
logger.error(`code: ${error.code}, method: ${req.method}, info: ${error.info || error.message}`); | |
res | |
.status(error.status) | |
.json(pick(['code', 'message', 'info'], error)); | |
}; | |
export const attachReply = (req: Request, res: App.Endpoint, next: NextFunction): void => { | |
res.reply = endpointFn.bind(null, res); | |
next(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment