Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,31 @@ declare global {
}
}

const responseEnhancer = () => (
const responseEnhancer = (definedMeta?: any) => (
req: Request,
res: Response,
next: NextFunction,
): void => {
res.formatter = _generateFormatters(res)
res.formatter = _generateFormatters(res, definedMeta)
next()
}

const _generateFormatters = (res: Response) => {
const _generateFormatters = (res: Response, definedMeta?: any) => {
const formatter = {} as ResponseFunction
let responseMeta = {}
let responseBody = {}

methods.map((method: Method) => {
if (method.isSuccess) {
formatter[method.name] = (data: any, meta: any) => {
responseBody = _generateSuccessResponse({ data, meta })
responseMeta = meta ? meta : definedMeta
responseBody = _generateSuccessResponse({ data, meta: responseMeta })
res.status(parseInt(method.code)).json(responseBody)
}
} else {
formatter[method.name] = (error: any, meta: any) => {
responseBody = _generateErrorResponse({ error, meta })
responseMeta = meta ? meta : definedMeta
responseBody = _generateErrorResponse({ error, meta: responseMeta })
res.status(parseInt(method.code)).json(responseBody)
}
}
Expand Down
32 changes: 31 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ const app = express()

describe('Test avaliable methods.', () => {
beforeAll(() => {
app.use(responseEnhancer())
const definedMEta = {
version: '1.0',
env: 'dev',
}
app.use(responseEnhancer(definedMEta))

app.get('/success-with-meta', function(req, res) {
const users = [{ name: 'John' }, { name: 'Jane' }]
Expand All @@ -15,6 +19,13 @@ describe('Test avaliable methods.', () => {
res.formatter.ok(users, metadata)
})

app.get('/success-with-defined-meta', function(req, res) {
const users = [{ name: 'John' }, { name: 'Jane' }]
// const metadata = { total: 2 }

res.formatter.ok(users)
})

app.get('/not-found', function(req, res) {
const meta = { trackId: '12345' }
const errors = [{ message: 'NOT_FOUND', detail: 'User not found.' }]
Expand Down Expand Up @@ -54,4 +65,23 @@ describe('Test avaliable methods.', () => {
done()
})
})

it('"formatter.notFound" should return status code "404" and correct payload', done => {
request(app)
.get('/success-with-defined-meta')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err)
expect(res.body).toEqual({
data: [{ name: 'John' }, { name: 'Jane' }],
meta: {
version: '1.0',
env: 'dev',
},
})
done()
})
})
})