Skip to content

Commit

Permalink
test: add example for beforeQuery param
Browse files Browse the repository at this point in the history
Related #219
  • Loading branch information
nodkz committed May 13, 2020
1 parent 8437357 commit a880f3e
Showing 1 changed file with 99 additions and 0 deletions.
99 changes: 99 additions & 0 deletions src/__tests__/github_issues/219-test.js
@@ -0,0 +1,99 @@
/* eslint-disable no-param-reassign */
/* @flow */

import { schemaComposer, graphql } from 'graphql-compose';
import { composeWithMongoose } from '../../index';
import { UserModel } from '../../__mocks__/userModel';

beforeAll(async () => {
await UserModel.base.connect();
await UserModel.create({
name: 'AAAAA',
age: 10,
});
await UserModel.create({
name: 'BBBBB',
age: 20,
});
});
afterAll(() => UserModel.base.disconnect());

const UserTC = composeWithMongoose(UserModel);

describe('issue #219 - Authorization using wrapResolve', () => {
it('correct request', async () => {
UserTC.wrapResolverResolve('findOne', (next) => (rp) => {
rp.beforeQuery = async (query) => {
// Choose any case or mix of them
// 1) check rp.context
// 2) make another query await Permission.find();
// 3) modify query = query.where({ perm: 'ALLOWED', userId: context?.req?.user?.id })
query = query.where({ age: { $gt: 19 } });

// 4) return cached data return UserCachedData[rp.args.id];
if (rp?.args?.filter?.name === 'CACHED') {
return { name: 'CACHED', age: 99 };
}

// 5) just check arg value
if (rp?.args?.filter?.name === 'ERROR') {
throw new Error('Wrong arg!');
}

return query.exec();
};
return next(rp);
});
schemaComposer.Query.addFields({
findUser: UserTC.getResolver('findOne'),
});
const schema = schemaComposer.buildSchema();
expect(
await graphql.graphql(
schema,
`query {
findUser(filter: { name: "AAAAA" }) {
name
age
}
}`
)
).toEqual({ data: { findUser: null } });

expect(
await graphql.graphql(
schema,
`query {
findUser(filter: { name: "BBBBB" }) {
name
age
}
}`
)
).toEqual({ data: { findUser: { age: 20, name: 'BBBBB' } } });

expect(
await graphql.graphql(
schema,
`query {
findUser(filter: { name: "CACHED" }) {
name
age
}
}`
)
).toEqual({ data: { findUser: { age: 99, name: 'CACHED' } } });

expect(
await graphql.graphql(
schema,
`query {
findUser(filter: { name: "ERROR" }) {
name
age
}
}`
)
).toEqual({ data: { findUser: null }, errors: [new Error('Wrong arg!')] });
});
});

0 comments on commit a880f3e

Please sign in to comment.