|
| 1 | +import { SchemaComposer, graphql } from 'graphql-compose'; |
| 2 | +import { composeMongoose } from '../../index'; |
| 3 | +import { mongoose } from '../../__mocks__/mongooseCommon'; |
| 4 | +import { Document } from 'mongoose'; |
| 5 | +import { convertSchemaToGraphQL } from '../../../src/fieldsConverter'; |
| 6 | +const schemaComposer = new SchemaComposer<{ req: any }>(); |
| 7 | + |
| 8 | +const AuthorSchema = new mongoose.Schema( |
| 9 | + { |
| 10 | + name: { type: String }, |
| 11 | + age: { type: Number }, |
| 12 | + isAlive: { type: Boolean }, |
| 13 | + }, |
| 14 | + { _id: false } |
| 15 | +); |
| 16 | + |
| 17 | +const BookSchema = new mongoose.Schema({ |
| 18 | + _id: { type: Number }, |
| 19 | + title: { type: String, required: true }, |
| 20 | + pageCount: { type: Number }, |
| 21 | + author: { type: AuthorSchema }, |
| 22 | +}); |
| 23 | + |
| 24 | +interface IAuthor { |
| 25 | + name: string; |
| 26 | + age: number; |
| 27 | + isAlive: boolean; |
| 28 | +} |
| 29 | + |
| 30 | +interface IBook extends Document { |
| 31 | + _id: number; |
| 32 | + title: string; |
| 33 | + author: IAuthor; |
| 34 | + pageCount?: number; |
| 35 | +} |
| 36 | + |
| 37 | +const BookModel = mongoose.model<IBook>('Book', BookSchema); |
| 38 | + |
| 39 | +convertSchemaToGraphQL(AuthorSchema, 'Author', schemaComposer); |
| 40 | + |
| 41 | +const BookTC = composeMongoose(BookModel, { schemaComposer }); |
| 42 | + |
| 43 | +schemaComposer.Query.addFields({ |
| 44 | + bookById: BookTC.mongooseResolvers.findById(), |
| 45 | + bookFindOne: BookTC.mongooseResolvers.findOne(), |
| 46 | + booksMany: BookTC.mongooseResolvers.findMany(), |
| 47 | +}); |
| 48 | + |
| 49 | +const schema = schemaComposer.buildSchema(); |
| 50 | + |
| 51 | +beforeAll(async () => { |
| 52 | + mongoose.set('debug', true); |
| 53 | + await BookModel.base.createConnection(); |
| 54 | + await BookModel.create({ |
| 55 | + _id: 1, |
| 56 | + title: 'Atlas Shrugged', |
| 57 | + author: { age: new Date().getFullYear() - 1905, isAlive: false, name: 'Ayn Rand' }, |
| 58 | + pageCount: 1168, |
| 59 | + }); |
| 60 | +}); |
| 61 | +afterAll(() => { |
| 62 | + mongoose.set('debug', false); |
| 63 | + BookModel.base.disconnect(); |
| 64 | +}); |
| 65 | + |
| 66 | +describe('nested projection - issue #271', () => { |
| 67 | + it('Happy Path', async () => { |
| 68 | + const result = await graphql.graphql({ |
| 69 | + schema, |
| 70 | + source: `query { |
| 71 | + booksMany { |
| 72 | + title |
| 73 | + pageCount |
| 74 | + author { name } |
| 75 | + } |
| 76 | + }`, |
| 77 | + contextValue: {}, |
| 78 | + }); |
| 79 | + console.log(JSON.stringify(result)); |
| 80 | + // expect(BookModel.find).toHaveBeenCalledTimes(1); |
| 81 | + // expect(BookModel.find).toHaveBeenCalledWith( |
| 82 | + // {}, |
| 83 | + // { limit: 1000, projection: { title: true, pageCount: true, 'author.name': true } } |
| 84 | + // ); |
| 85 | + }); |
| 86 | +}); |
0 commit comments