Skip to content

Instantly share code, notes, and snippets.

@timsuchanek
Created July 14, 2020 16:50
Show Gist options
  • Save timsuchanek/971d39047348e27190f667b8811f9d52 to your computer and use it in GitHub Desktop.
Save timsuchanek/971d39047348e27190f667b8811f9d52 to your computer and use it in GitHub Desktop.
type Middleware = (
query: any,
next: (query: any) => Promise<any>,
) => Promise<any>
class Client {
middlewares: Middleware[] = []
async query(query) {
return this.buildQuery(query, this.middlewares.slice())
}
private async buildQuery(query, middlewares: Middleware[]) {
const middleware = middlewares.shift()
if (middleware) {
return middleware(query, (query2) => this.buildQuery(query2, middlewares))
} else {
return this.resolve(query)
}
}
private resolve(query) {
return Promise.resolve({ query, data: {} })
}
use(middleware: Middleware) {
this.middlewares.push(middleware)
}
}
const client = new Client()
client.use(async (query, next) => {
console.log('1')
query.x = 2
const data = await next(query)
console.log('4')
return data
})
client.use(async (query, next) => {
console.log('2')
query.x = 3
const data = await next(query)
console.log('3')
return data
})
client.query({ hello: 'world' }).then(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment