Skip to content

Commit

Permalink
Can update status code in before/after function
Browse files Browse the repository at this point in the history
  • Loading branch information
Maxime Magné committed Sep 15, 2020
1 parent 7534617 commit 22befe4
Show file tree
Hide file tree
Showing 9 changed files with 40 additions and 25 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# HearthJS

### v2.6.5
- Can update status code in before/after callback

### v2.6.4
- Add auth token in cookie and in Authorization header

Expand Down
9 changes: 5 additions & 4 deletions docs/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,25 +39,26 @@ You can add following keys to a schema
}
```

In the `before` and `after` function, if you want return an error, pass a string to the next function. It will return an error with your defined string as message. If you receive data in `after` function, they will not be sent.
In the `before` and `after` function, if you want return an error, pass a string to the next function. It will return an error with your defined string as message. If you receive data in `after` function, they will not be sent.
You can update the status code in before/after function.

```js
{
before: (req, res, next) => {
next('Error') // Will return Error as message to the user
next('Error', 400) // Will return Error as message to the user
}
}
```

You can update `data` return by next by giving it the new `data`.
You can update `data` returned by next by giving it the new `data`.

```js
{
after: (req, res, data, next) => {
let newData = {
firstname: 'John'
}
next(null, newData) // Will return Error as message to the user
next(null, 200, newData) // Will return Error as message to the user
}
}
```
Expand Down
14 changes: 7 additions & 7 deletions lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ const api = {

// Return error if there is
if (result.valid === false) {
return res.json(this.createResponse(req, false, {}, result.message))
return res.status(400).json(this.createResponse(req, false, {}, result.message))
}

this._execBefore(req, res, schema)
Expand Down Expand Up @@ -256,10 +256,10 @@ const api = {

_execBefore: function (req, res, schema) {
// Execute before
this._mayExec(req, res, schema.before, 'before', (err) => {
this._mayExec(req, res, schema.before, 'before', (err, code) => {
if (err) {
logger.log(err.toString(), 'error')
return res.json(this.createResponse(req, false, {}, err.toString()))
return res.status(code || 400).json(this.createResponse(req, false, {}, err.toString()))
}

if (schema.query !== undefined) {
Expand All @@ -269,7 +269,7 @@ const api = {
database.exec(schema.query, req, model, (err, result, formatted) => {
if (err) {
logger.log(err.toString(), 'error')
return res.json(this.createResponse(req, false, {}, 'An error occured'))
return res.status(500).json(this.createResponse(req, false, {}, 'An error occured'))
}

// Execute after
Expand All @@ -290,13 +290,13 @@ const api = {
* @param {Object} schema Route schema
*/
_execAfter: function (req, res, data, schema) {
this._mayExec(req, res, schema.after, 'after', data, (err, newData) => {
this._mayExec(req, res, schema.after, 'after', data, (err, code, newData) => {
if (err) {
logger.log(err.toString(), 'error')
return res.json(this.createResponse(req, false, {}, err.toString()))
return res.status(code || 400).json(this.createResponse(req, false, {}, err.toString()))
}
data = (newData !== undefined) ? newData : data
return res.json(this.createResponse(req, true, data, (schema.successMsg === undefined) ? '' : schema.successMsg))
return res.status(code || 200).json(this.createResponse(req, true, data, (schema.successMsg === undefined) ? '' : schema.successMsg))
})
},

Expand Down
12 changes: 10 additions & 2 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,17 @@ const server = {
*/
_initErrorMiddleware: function () {
this._app.use((err, req, res, next) => {
return res.json({
let message = err.toString()
let code = 400

if (err.message !== undefined) {
message = err.message
code = err.code || 400
}

return res.status(code).json({
success: false,
message: err.toString()
message: message
})
})
},
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "hearthjs",
"version": "2.6.4",
"version": "2.6.5",
"description": "A NodeJS server framework to build fast Rest API",
"main": "lib/index.js",
"bin": "bin/hearthjs",
Expand Down
4 changes: 2 additions & 2 deletions test/datasets/myApp/server/api/apiName/api.apiName.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ let myMiddleware = function (req, res, next) {
const schemas = {
getSchemaA: {
before: (req, res, next) => {
next(t('Error...', 'fr'))
next(t('Error...', 'fr'), 402)
}
},

Expand Down Expand Up @@ -96,7 +96,7 @@ const schemas = {
}],

after: (req, res, data, next) => {
next(null, req.body)
next(null, 201, req.body)
}
},

Expand Down
2 changes: 1 addition & 1 deletion test/datasets/mySQLApp/server/api/apiName/api.apiName.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const schemas = {
let newData = {
person: data[0].firstname + ' ' + data[0].lastname
}
next(null, newData)
next(null, 200, newData)
},
successMsg: 'Success'
},
Expand Down
4 changes: 2 additions & 2 deletions test/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ describe('Logger', () => {
let _logContent = fs.readFileSync(_logFilePath, 'utf8')
assert.strictEqual(_logContent.includes('GET /crash started'), true)
assert.strictEqual(_logContent.includes('GET /crash ended in'), false)
assert.strictEqual(_logContent.includes('(200)'), false)
assert.strictEqual(_logContent.includes('(400)'), false)
done()
})
})
Expand Down Expand Up @@ -374,7 +374,7 @@ function executeCluster (mode, nbCluster, port, callback) {

setTimeout(() => {
return callback()
}, 1000)
}, 1500)
}

/**
Expand Down
15 changes: 9 additions & 6 deletions test/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,10 @@ describe('Server', () => {
app.close(done)
})

it('should serve schema-a route which return an error', function (done) {
it('should serve schema-a route which return an error and update status code in before', function (done) {
request.get(app.server.getEndpoint() + 'schema-a', function (err, response, body) {
assert.strictEqual(err, null)
assert.strictEqual(response.statusCode, 402)
body = JSON.parse(body)
assert.strictEqual(body.success, false)
assert.strictEqual(body.message, 'Error...')
Expand Down Expand Up @@ -239,7 +240,7 @@ describe('Server', () => {
})
})

it('should validate in data', (done) => {
it('should validate in data and update status code in after', (done) => {
let accounts = [{
name: 'Account1',
users: [{
Expand All @@ -256,6 +257,7 @@ describe('Server', () => {
json: { accounts: accounts }
}, function (err, response, body) {
assert.strictEqual(err, null)
assert.strictEqual(response.statusCode, 201)
assert.deepStrictEqual(body, {
success: true,
data: { accounts: accounts },
Expand All @@ -282,6 +284,7 @@ describe('Server', () => {
json: { accounts: accounts }
}, function (err, response, body) {
assert.strictEqual(err, null)
assert.strictEqual(response.statusCode, 400)
assert.deepStrictEqual(body, {
success: false,
data: {},
Expand Down Expand Up @@ -603,7 +606,7 @@ describe('Server', () => {
done()
})
})
})
}).timeout(5000)

it('should take the port send via CLI', (done) => {
executeCluster('1', '4000', () => {
Expand All @@ -613,7 +616,7 @@ describe('Server', () => {
done()
})
})
})
}).timeout(5000)

it('should load balance between all workers 2 workers', (done) => {
executeCluster('2', '8080', () => {
Expand Down Expand Up @@ -745,7 +748,7 @@ describe('Server', () => {
}
}
})
}).timeout(6000)
}).timeout(10000)
})
})

Expand All @@ -765,7 +768,7 @@ function executeCluster (nbCluster, port, callback) {

setTimeout(() => {
return callback()
}, 1000)
}, 1500)
}

/**
Expand Down

0 comments on commit 22befe4

Please sign in to comment.