Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Middleware support to Mirage #41

Open
samselikoff opened this issue Feb 4, 2020 · 1 comment
Open

Add Middleware support to Mirage #41

samselikoff opened this issue Feb 4, 2020 · 1 comment

Comments

@samselikoff
Copy link
Contributor

Over in miragejs/miragejs#267 @asantos00 kicked off an idea for adding middleware to Mirage.

We've definitely needed something like this for a while.

We should discuss possible APIs here. Ideally just borrow from the latest + greatest implementation in server frameworks that we like the best.

IanVS pushed a commit to miragejs/miragejs that referenced this issue Oct 30, 2023
Relating to [Add Middleware support to Mirage #41 ](miragejs/discuss#41).

# Middleware

This PR adds middleware to miragejs via a new `server.midleware = [...]`

Example middleware which randomly returns a 500 response:
```js
  function random500() {
    return (schema, req, next) => {
      return (Math.random() > 0.7)
        ? new Response(500, {}, 'no')
        : next();
    }
  }
```
  
Routes which use the middleware defined above: 
_(Edited to match latest update)_
```js
  routes() {
    this.middleware = [
      random500(),
      addABunchOfResponseHeaders(),
      // more middleware can be added here...
    ]

    // Subsequent routes will have that middleware
    this.get('/users', (schema, req) => {
      return new Response(204, {}, null);
    });

    this.middleware = [
      // differentMiddleware
    ]
     
    this.get('/frogs', (schema, req) => {
      return new Response(204, {}, null);
    });
  }
```
# Not included

1. There's a bit of funkyness when middleware wants to modify the response from a route handler because the route handler might return a `Response` object or it might return something else altogether.  I imagine this could be addressed separately.

2. `async` middleware - again, could be added after (if this is the approach this repo heads in).
@nomnomnomnom
Copy link

Middleware support added in 0.1.48. I believe this issue can be closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants