apollo-datasource-mongodb
apollo-datasource-mongodb copied to clipboard
`initialize()` retrieve user
I would like to store the authenticated user in the context, in order for each method of the DataSource
to directly access it, but I think it may be an antipattern. I'm not even sure async initialize()
is allowed.
async initialize(config: DataSourceConfig<GraphQLContext>) {
super.initialize?.(config)
const user = await this.findBearerUser()
this.context.user = user
}
This would allow the following (no need for user fetching):
async findOneById(id) {
if (!this.context.user) throw new Error('Unauthenticated.')
// ...
}
Instead of fetching the user for every method:
async findOneById(id) {
const user = await this.findBearerUser()
if (!user) throw new Error('Unauthenticated.')
// ...
}
What's the best way to achieve the desired behavior? Are we constrained to fetch the user on every method?