Express: How could I use `return 'ok'` instead `res.send('ok')`

Created on 4 Dec 2018  路  2Comments  路  Source: expressjs/express

If there are some conditional breaks, I have to use return res.send('ok'), I wanna just use return 'ok' in every route handlers.

Just like this:

app.get('/', () => 'ok')
question

Most helpful comment

@wxs77577 one way is to add a small "sugar"-method yourself to add routes that returns the result. I personally use something like this in a few servers:

const express = require('express')

/* ... */

const app = express()

function route (method, path, handler) {
  app[method](path, (req, res, next) => {
    handler(req)
      .then(result => result ? res.json(result) : res.status(204).end(''))
      .catch(next)
  })
}

route('get', '/v1/version', async () => ({ version: packageInfo.version }))

route('post', '/v1/users', userCtrl.post)

route('post', '/v1/login-sessions', loginCtrl.initiate)
route('post', '/v1/login-sessions/:sessionId/finalize', loginCtrl.finalize)

/* ... */

All 2 comments

Hey @wxs77577, this is not currently possible in express. Like you said in your question, the way is to just res.send.

@wxs77577 one way is to add a small "sugar"-method yourself to add routes that returns the result. I personally use something like this in a few servers:

const express = require('express')

/* ... */

const app = express()

function route (method, path, handler) {
  app[method](path, (req, res, next) => {
    handler(req)
      .then(result => result ? res.json(result) : res.status(204).end(''))
      .catch(next)
  })
}

route('get', '/v1/version', async () => ({ version: packageInfo.version }))

route('post', '/v1/users', userCtrl.post)

route('post', '/v1/login-sessions', loginCtrl.initiate)
route('post', '/v1/login-sessions/:sessionId/finalize', loginCtrl.finalize)

/* ... */
Was this page helpful?
0 / 5 - 0 ratings

Related issues

snowdream picture snowdream  路  3Comments

guyisra picture guyisra  路  3Comments

prashantLio picture prashantLio  路  3Comments

despairblue picture despairblue  路  3Comments

haider0324 picture haider0324  路  3Comments