Skip to content

Commit c2449a9

Browse files
committed
test: check projection with addRelation method
closes #370
1 parent 89c5328 commit c2449a9

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import { SchemaComposer, graphql } from 'graphql-compose';
2+
import { composeMongoose } from '../../index';
3+
import { mongoose } from '../../__mocks__/mongooseCommon';
4+
import { Schema } from 'mongoose';
5+
6+
const schemaComposer = new SchemaComposer<{ req: any }>();
7+
8+
// mongoose.set('debug', true);
9+
10+
const UserSchema = new mongoose.Schema({
11+
firstName: {
12+
type: String,
13+
required: true,
14+
},
15+
_organizationIds: [
16+
{
17+
type: Schema.Types.ObjectId,
18+
ref: 'Organization',
19+
index: true,
20+
},
21+
],
22+
});
23+
const UserModel = mongoose.model('User', UserSchema);
24+
const UserTC = composeMongoose(UserModel, { schemaComposer });
25+
26+
const OrganizationSchema = new mongoose.Schema({
27+
title: {
28+
type: String,
29+
required: true,
30+
},
31+
});
32+
const OrganizationModel = mongoose.model('Organization', OrganizationSchema);
33+
const OrganizationTC = composeMongoose(OrganizationModel, { schemaComposer });
34+
35+
UserTC.addRelation('organizations', {
36+
resolver: () => OrganizationTC.mongooseResolvers.findByIds(),
37+
prepareArgs: {
38+
_ids: (source: any) => source._organizationIds,
39+
skip: null,
40+
sort: null,
41+
},
42+
projection: { _organizationIds: 1 },
43+
});
44+
45+
schemaComposer.Query.addFields({
46+
users: UserTC.mongooseResolvers.findMany(),
47+
});
48+
49+
const schema = schemaComposer.buildSchema();
50+
51+
beforeAll(async () => {
52+
await OrganizationModel.base.createConnection();
53+
const orgs = await OrganizationModel.create([
54+
{ title: 'Org1' },
55+
{ title: 'Org2' },
56+
{ title: 'Org3' },
57+
]);
58+
await UserModel.create([
59+
{ firstName: 'User1', _organizationIds: [orgs[0]._id, orgs[1]._id] },
60+
{ firstName: 'User2', _organizationIds: [orgs[2]._id] },
61+
]);
62+
});
63+
afterAll(() => {
64+
OrganizationModel.base.disconnect();
65+
});
66+
67+
describe('issue #370 - addRelation: projection not working as expected ', () => {
68+
it('check', async () => {
69+
const result = await graphql.graphql({
70+
schema,
71+
source: `query {
72+
users {
73+
firstName
74+
organizations {
75+
title
76+
}
77+
}
78+
}`,
79+
});
80+
expect(result).toEqual({
81+
data: {
82+
users: [
83+
{ firstName: 'User1', organizations: [{ title: 'Org1' }, { title: 'Org2' }] },
84+
{ firstName: 'User2', organizations: [{ title: 'Org3' }] },
85+
],
86+
},
87+
});
88+
});
89+
});

0 commit comments

Comments
 (0)