Open DeveloperRic opened 3 years ago
I think the more supported way of doing what you're trying to achieve is with resolve wrappers. I used resolver wrappers in my app to ensure that users can only read and write their own models, based on a userId
field on every model. It took a while to get the types right, but my code is now type safe. Maybe you can do something similar and find a way to refactor your guardResolver
to use beforeRecordMutate
and beforeQuery
.
Thanks for the suggestion, I was able to use resolve wrappers in my solution & it made it a lot cleaner 😃. However, the type error still exists. Here is my updated guard function:
export function guardResolver<TSource, TContext, TArgs, TReturn>(
resolver: Resolver<TSource, TContext, TArgs, TReturn>,
...guards: Guard<TContext, TArgs, TReturn>[]
): Resolver<TSource, TContext, TArgs, TReturn> {
const guardedResolver = resolver.wrapResolve(next => async params => {
// check ingress guards
for (const guard of guards.filter(guard => guard.type == 'ingress')) {
const result = await guard.check({
args: params.args,
context: params.context
})
if (!result) continue
if (result.args) params.args = result.args
}
// get the data
let data: TReturn | undefined = await next(params)
// check egress guards
for (const guard of guards.filter(guard => guard.type == 'egress')) {
const result = await guard.check({
args: params.args,
context: params.context,
data
})
if (!result) continue
if (result.args) params.args = result.args
if (result.data !== null) {
// data is being mutated
if (result.data === false) data = undefined
else data = result.data
}
}
return data
})
return guardedResolver
}
This line still raises type errors:
chatMany: guardResolver(ChatTC.mongooseResolvers.findMany(), new ContainsOnlyOwnChatsGuard())
because findMany()
incorrectly declares its return type as TDoc
instead of TDoc[]
and ContainsOnlyOwnChatsGuard
expects the type IChat[]
(which is consistent with the actual data returned by the findMany resolver)
Hi, I am working on custom guards around resolvers including
findOne, findMany, etc.
I have hit a couple of problems:TArgs
) aren't exported, and so I cannot enforce consistent typing (for args) on the guarding resolver.findMany
resolver declares its type asResolver<TSource = any, TContext = any, TDoc extends Document = any>
. This is inconsistent with the return value (the resolver returnsTDoc[]
, notTDoc
), and so type enforcement breaks again.For context, here is my Guard class:
... and here is an example of how I use it:
In the above example, at the moment, TS will raise an error for
ContainsOnlyOwnChatsGuard
because it expectsIChat[]
whereasfindMany()
declares that it will returnIChat
(despite the fact that it returnsIChat[]
).console.log
of the output is below:I don't know the extent to which these problems exist in the library, any help is appreciated.