yoga2 icon indicating copy to clipboard operation
yoga2 copied to clipboard

Support middlewares out-of-the-box

Open Weakky opened this issue 6 years ago • 4 comments

Description

There are two types of middleware that should be easily definable with Yoga:

  • "HTTP" middleware: most probably express middlewares
  • GraphQL middleware: a function to be run before (or after) a resolver is executed
    • middlewares should be definable at every level (globally, type-level, field-level)

Current state:

  • HTTP middleware: Only possible by ejecting
  • GraphQL middleware: Only possible by ejecting (eg: using graphql-middleware)

Ideally, both HTTP middlewares and GraphQL middlewares should be definable without having to eject.

Unfortunately, because Yoga doesn't require a server to be defined by default, users have no way to access the underlying components.

  • Fortunately, for GraphQL middlewares, this can be done on the schema layer and thus should be handled by nexus (Proposal here: https://github.com/prisma/nexus/issues/64)
  • For HTTP middlewares however, we need to find an elegant way to expose the underlying express instance for people to compose with it

Motivation

Obvious use-cases:

  • Authorization (#34)
  • Authentication (#35)
  • Logging
  • Input validation
  • ...

Some ideas

Accessing the underlying express instance

Option 1

Have an express folder, in which all files gets the underlying express instance injected

export default ({ app }) => {
  // app.use(passport.initialize())
  // app.post('/login', ...)
}

Option 2

Do we really need several files in a folder? What about a single express.ts file ?

import { logging, otherMiddleware } from './express-middleware'

export default ({ app }) => {
  // app.use(logging)  
  // app.post('/login', otherMiddleware, handler)
  // app.post('/logout', otherMiddleware, handler)
}

Option 3

Any better idea?


Because HTTP middlewares and GraphQL middlewares are two different concepts, it feels hard to come up with an API that elegantly conciles the two.

We'd love to hear feedback/different API design for express middlewares as well as nexus middlewares 🙌

Thanks!

Weakky avatar Mar 01 '19 14:03 Weakky

Option 2 was released under [email protected] for accessing express middlewares

Weakky avatar Mar 14 '19 18:03 Weakky

Thanks for this @Weakky! I'm very curious to see graphql middlewares support without ejecting soon. Until then, I'll simply eject (since it's a reversible process 😄 )

DevanB avatar Mar 16 '19 19:03 DevanB

Would be great if someone clarified how Prisma 2, Yoga 2 and Prisma Nexus are or will be related 😓 I'm kinda lost here. There are so many moving parts changing as I'm typing it.

ivan-kleshnin avatar Mar 22 '19 09:03 ivan-kleshnin

@ivan-kleshnin I think this question is better asked in the Prisma forum for all to see there, not as a comment on a middlewares discussion issue.

DevanB avatar Mar 24 '19 00:03 DevanB