Skip to content

Commit a351ec1

Browse files
committed
test: add demo for issue 135
1 parent f94fa7d commit a351ec1

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/* @flow */
2+
/* eslint-disable no-await-in-loop */
3+
4+
import mongoose from 'mongoose';
5+
import MongodbMemoryServer from 'mongodb-memory-server';
6+
import { schemaComposer, graphql } from 'graphql-compose';
7+
import { composeWithMongoose } from '../../index';
8+
9+
let mongoServer;
10+
beforeAll(async () => {
11+
mongoServer = new MongodbMemoryServer();
12+
const mongoUri = await mongoServer.getConnectionString();
13+
await mongoose.connect(
14+
mongoUri,
15+
{ useNewUrlParser: true }
16+
);
17+
// mongoose.set('debug', true);
18+
});
19+
20+
afterAll(() => {
21+
mongoose.disconnect();
22+
mongoServer.stop();
23+
});
24+
25+
// May require additional time for downloading MongoDB binaries
26+
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
27+
28+
describe('issue #135 - Mongoose virtuals', () => {
29+
const RecordSchema = new mongoose.Schema({ id: String, title: String });
30+
31+
// ADD VIRTUAL FIELDS VIA loadClass METHOD
32+
// see https://mongoosejs.com/docs/api.html#schema_Schema-loadClass
33+
class RecordDoc {
34+
get virtualField123() {
35+
// $FlowFixMe
36+
return `Improved ${this.title}`;
37+
}
38+
}
39+
RecordSchema.loadClass(RecordDoc);
40+
41+
// ADD MOCK DATA TO DB
42+
const Record = mongoose.model('Record', RecordSchema);
43+
beforeAll(async () => {
44+
for (let i = 1; i <= 3; i++) {
45+
// $FlowFixMe
46+
await Record.create({ _id: `10000000000000000000000${i}`, title: `Title ${i}` });
47+
}
48+
});
49+
50+
// ADD VIRTUAL FIELD DEFINITION <------------------- JUST ADD FIELD DEFINITION 🛑🛑🛑
51+
// no need to define resolve method explicitly
52+
const RecordTC = composeWithMongoose(Record);
53+
RecordTC.addFields({
54+
virtualField123: {
55+
type: 'String',
56+
},
57+
});
58+
59+
// INIT GRAPHQL SCHEMA
60+
schemaComposer.Query.addFields({
61+
findMany: RecordTC.getResolver('findMany'),
62+
});
63+
64+
const schema = schemaComposer.buildSchema();
65+
66+
it('check that virtual field works', async () => {
67+
const res = await graphql.graphql({
68+
schema,
69+
source: 'query { findMany { id title virtualField123 } }',
70+
});
71+
72+
expect(res).toEqual({
73+
data: {
74+
findMany: [
75+
{ id: null, title: 'Title 1', virtualField123: 'Improved Title 1' },
76+
{ id: null, title: 'Title 2', virtualField123: 'Improved Title 2' },
77+
{ id: null, title: 'Title 3', virtualField123: 'Improved Title 3' },
78+
],
79+
},
80+
});
81+
});
82+
});

0 commit comments

Comments
 (0)