abernier / uest

https://www.npmjs.com/package/uest
9 stars 1 forks source link

Build Status NPM version David Coveralls github

req.uest is an Express middleware that allows you, from a given route, to request another route.

Features are:

It allows you to decouple your app's routes from your API's ones. IOW, your app routes can now consume your API as any client.

Install

$ npm i uest
// app.js

const uest = require('uest')

app.use(uest())

Usage

req.uest(options, (er, resp, body) => {})

It also supports await:

const [resp, body] = await req.uest(options)

Example

// Mount our API router
app.use('/api', require('./routers/api'));

//
// App routing
//

app.post('/login', (req, res, next) => {
  const {email, password} = req.body

  //
  // Our subsequent request to `POST /api/sessions` route
  //

  req.uest({
    method: 'POST',
    url: '/api/sessions',
    body: {email, password}
  }, (er, resp, body) => {
    if (er) {
      // Deal with specific "Forbidden" error
      if (er.status === 403) {
        return res.render('login', {error: "Wrong login/password"})
      }

      return next(er); // for any other error
    }

    console.log('User-session created for', body.user)

    // `req.session` is up-to-date
    console.log(`Welcome back ${req.session.user.firstname}!`

    res.redirect('/profile')
  })
});