Skip to content

Commit 72fb754

Browse files
authored
refactor: due changes in [email protected]
BREAKING CHANGE: Using API from [email protected]
1 parent a7e5bf6 commit 72fb754

File tree

81 files changed

+937
-805
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+937
-805
lines changed

.markdownlint.json

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"line-length": false,
3+
"no-trailing-punctuation": {
4+
"punctuation": ",;"
5+
},
6+
"no-inline-html": false,
7+
"ol-prefix": false,
8+
"first-line-h1": false,
9+
"first-heading-h1": false,
10+
"no-bare-urls": false
11+
}

.vscode/settings.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"prettier.eslintIntegration": true,
3+
"eslint.validate": [
4+
"javascript",
5+
],
6+
"javascript.validate.enable": false
7+
}

README.md

Lines changed: 61 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,32 @@
22

33
[![travis build](https://img.shields.io/travis/graphql-compose/graphql-compose-mongoose.svg)](https://travis-ci.org/graphql-compose/graphql-compose-mongoose)
44
[![codecov coverage](https://img.shields.io/codecov/c/github/graphql-compose/graphql-compose-mongoose.svg)](https://codecov.io/github/graphql-compose/graphql-compose-mongoose)
5-
[![](https://img.shields.io/npm/v/graphql-compose-mongoose.svg)](https://www.npmjs.com/package/graphql-compose-mongoose)
6-
[![npm](https://img.shields.io/npm/dt/graphql-compose-mongoose.svg)](http://www.npmtrends.com/graphql-compose-mongoose)
5+
[![npm](https://img.shields.io/npm/v/graphql-compose-mongoose.svg)](https://www.npmjs.com/package/graphql-compose-mongoose)
6+
[![trends](https://img.shields.io/npm/dt/graphql-compose-mongoose.svg)](http://www.npmtrends.com/graphql-compose-mongoose)
77
[![Join the chat at https://gitter.im/graphql-compose/Lobby](https://badges.gitter.im/graphql-compose/graphql-compose.svg)](https://gitter.im/graphql-compose/Lobby)
88
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
99
[![Greenkeeper badge](https://badges.greenkeeper.io/graphql-compose/graphql-compose-mongoose.svg)](https://greenkeeper.io/)
1010

11-
1211
This is a plugin for [graphql-compose](https://github.com/graphql-compose/graphql-compose), which derives GraphQLType from your [mongoose model](https://github.com/Automattic/mongoose). Also derives bunch of internal GraphQL Types. Provide all CRUD resolvers, including `graphql connection`, also provided basic search via operators ($lt, $gt and so on).
1312

1413
## Installation
15-
```
14+
15+
```bash
1616
npm install graphql graphql-compose mongoose graphql-compose-mongoose --save
1717
```
18+
1819
Modules `graphql`, `graphql-compose`, `mongoose` are in `peerDependencies`, so should be installed explicitly in your app. They have global objects and should not have ability to be installed as submodule.
1920

2021
If you want to add additional resolvers [`connection`](https://github.com/graphql-compose/graphql-compose-connection) and/or [`pagination`](https://github.com/graphql-compose/graphql-compose-pagination) - just install following packages and `graphql-compose-mongoose` will add them automatically.
21-
```
22+
23+
```bash
2224
npm install graphql-compose-connection graphql-compose-pagination --save
2325
```
2426

25-
#### Different builds
27+
### Different builds
28+
2629
This library contains different builds for any purposes:
30+
2731
```js
2832
// Default import for using under node v6 and above
2933
import { composeWithMongoose } from 'graphql-compose-mongoose';
@@ -42,10 +46,11 @@ Live demo: [https://graphql-compose.herokuapp.com/](https://graphql-compose.hero
4246
Source code: https://github.com/graphql-compose/graphql-compose-examples
4347

4448
Small explanation for variables naming:
49+
4550
- `UserSchema` - this is a mongoose schema
4651
- `User` - this is a mongoose model
47-
- `UserTC` - this is a `TypeComposer` instance for User. `TypeComposer` has `GraphQLObjectType` inside, avaliable via method `UserTC.getType()`.
48-
- Here and in all other places of code variables suffix `...TC` means that this is `TypeComposer` instance, `...ITC` - `InputTypeComposer`, `...ETC` - `EnumTypeComposer`.
52+
- `UserTC` - this is a `ObjectTypeComposer` instance for User. `ObjectTypeComposer` has `GraphQLObjectType` inside, avaliable via method `UserTC.getType()`.
53+
- Here and in all other places of code variables suffix `...TC` means that this is `ObjectTypeComposer` instance, `...ITC` - `InputTypeComposer`, `...ETC` - `EnumTypeComposer`.
4954

5055
```js
5156
import mongoose from 'mongoose';
@@ -118,14 +123,16 @@ schemaComposer.Mutation.addFields({
118123
const graphqlSchema = schemaComposer.buildSchema();
119124
export default graphqlSchema;
120125
```
126+
121127
That's all!
122128
You think that is to much code?
123129
I don't think so, because by default internally was created about 55 graphql types (for input, sorting, filtering). So you will need much much more lines of code to implement all these CRUD operations by hands.
124130

125-
126131
### Working with Mongoose Collection Level Discriminators
132+
127133
Variable Namings
128-
* `...DTC` - Suffix for a `DiscriminatorTypeComposer` instance, which is also an instance of `TypeComposer`. All fields and Relations manipulations on this instance affects all registered discriminators and the Discriminator Interface.
134+
135+
- `...DTC` - Suffix for a `DiscriminatorTypeComposer` instance, which is also an instance of `ObjectTypeComposer`. All fields and Relations manipulations on this instance affects all registered discriminators and the Discriminator Interface.
129136

130137
```js
131138
import mongoose from 'mongoose';
@@ -196,7 +203,7 @@ Variable Namings
196203
const PersonTC = CharacterDTC.discriminator(PersonModel); // baseOptions -> customisationsOptions applied
197204

198205
// You may now use CharacterDTC to add fields to all Discriminators
199-
// Use DroidTC, `PersonTC as any other TypeComposer.
206+
// Use DroidTC, `PersonTC as any other ObjectTypeComposer.
200207
schemaComposer.Mutation.addFields({
201208
droidCreate: DroidTC.getResolver('createOne'),
202209
personCreate: PersonTC.getResolver('createOne'),
@@ -246,6 +253,7 @@ Variable Namings
246253
## FAQ
247254

248255
### Can I get generated vanilla GraphQL types?
256+
249257
```js
250258
const UserTC = composeWithMongoose(User);
251259
UserTC.getType(); // returns GraphQLObjectType
@@ -255,9 +263,10 @@ UserTC.get('fieldWithNesting.subNesting').getType(); // get GraphQL type of deep
255263
```
256264

257265
### How to add custom fields?
266+
258267
```js
259268
UserTC.addFields({
260-
lonLat: TypeComposer.create('type LonLat { lon: Float, lat: Float }'),
269+
lonLat: ObjectTypeComposer.create('type LonLat { lon: Float, lat: Float }'),
261270
notice: 'String', // shorthand definition
262271
noticeList: { // extended
263272
type: '[String]', // String, Int, Float, Boolean, ID, Json
@@ -272,7 +281,9 @@ UserTC.addFields({
272281
```
273282

274283
### How to build nesting/relations?
284+
275285
Suppose you `User` model has `friendsIds` field with array of user ids. So let build some relations:
286+
276287
```js
277288
UserTC.addRelation(
278289
'friends',
@@ -305,10 +316,12 @@ UserTC.addRelation(
305316
```
306317

307318
### Reusing the same mongoose Schema in embedded object fields
319+
308320
Suppose you have a common structure you use as embedded object in multiple Schemas.
309321
Also suppose you want the structure to have the same GraphQL type across all parent types.
310322
(For instance, to allow reuse of fragments for this type)
311323
Here are Schemas to demonstrate:
324+
312325
```js
313326
import { Schema } from 'mongoose';
314327

@@ -330,16 +343,20 @@ const Article = Schema({
330343
heroImage: ImageDataStructure
331344
});
332345
```
346+
333347
If you want the `ImageDataStructure` to use the same GraphQL type in both `Article` and `UserProfile` you will need create it as a mongoose schema (not a standard javascript object) and to explicitly tell `graphql-compose-mongoose` the name you want it to have. Otherwise, without the name, it would generate the name according to the first parent this type was embedded in.
334348

335349
Do the following:
350+
336351
```js
337352
import { schemaComposer } from 'graphql-compose'; // get the default schemaComposer or your created schemaComposer
338353
import { convertSchemaToGraphQL } from 'graphql-compose-mongoose';
339354

340355
convertSchemaToGraphQL(ImageDataStructure, 'EmbeddedImage', schemaComposer); // Force this type on this mongoose schema
341356
```
357+
342358
Before continuing to convert your models to TypeComposers:
359+
343360
```js
344361
import mongoose from 'mongoose';
345362
import { composeWithMongoose } from 'graphql-compose-mongoose';
@@ -350,7 +367,9 @@ const Article = mongoose.model('Article', Article);
350367
const UserProfileTC = composeWithMongoose(UserProfile);
351368
const ArticleTC = composeWithMongoose(Article);
352369
```
370+
353371
Then, you can use queries like this:
372+
354373
```graphql
355374
query {
356375
topUser {
@@ -375,16 +394,18 @@ fragment fullImageData on EmbeddedImage {
375394
```
376395

377396
### Access and modify mongoose doc before save
397+
378398
This library provides some amount of ready resolvers for fetch and update data which was mentioned above. And you can [create your own resolver](https://github.com/graphql-compose/graphql-compose) of course. However you can find that add some actions or light modifications of mongoose document directly before save at existing resolvers appears more simple than create new resolver. Some of resolvers accepts *before save hook* which can be provided in *resolver params* as param named `beforeRecordMutate`. This hook allows to have access and modify mongoose document before save. The resolvers which supports this hook are:
379399

380-
* createOne
381-
* createMany
382-
* removeById
383-
* removeOne
384-
* updateById
385-
* updateOne
400+
- createOne
401+
- createMany
402+
- removeById
403+
- removeOne
404+
- updateById
405+
- updateOne
386406

387407
The prototype of before save hook:
408+
388409
```js
389410
(doc: mixed, rp: ExtendedResolveParams) => Promise<*>,
390411
```
@@ -443,40 +464,42 @@ schemaComposer.Mutation.addFields({
443464
}),
444465
});
445466
```
467+
446468
### How can I push/pop or add/remove values to arrays?
469+
447470
The default resolvers, by design, will replace (overwrite) any supplied array object when using e.g. `updateById`. If you want to push or pop a value in an array you can use a custom resolver with a native MongoDB call.
448471

449472
For example (push):-
450473

451-
```javascript
474+
```js
452475
// Define new resolver 'pushToArray'
453476
UserTC.addResolver({
454-
name: 'pushToArray',
455-
type: UserTC,
456-
args: { userId: 'MongoID!', valueToPush: 'String' },
457-
resolve: async ({ source, args, context, info }) => {
458-
const user = await User.update({ _id: args.userId }, { $push: { arrayToPushTo: args.valueToPush } } })
459-
if (!user) return null // or gracefully return an error etc...
460-
return User.findOne({ _id: args.userId }) // return the record
461-
}
477+
name: 'pushToArray',
478+
type: UserTC,
479+
args: { userId: 'MongoID!', valueToPush: 'String' },
480+
resolve: async ({ source, args, context, info }) => {
481+
const user = await User.update({ _id: args.userId }, { $push: { arrayToPushTo: args.valueToPush } } })
482+
if (!user) return null // or gracefully return an error etc...
483+
return User.findOne({ _id: args.userId }) // return the record
484+
}
462485
})
463486

464487
// Then add 'pushToArray' as a graphql field e.g.
465-
schemaComposer.rootMutation().addFields({userPushToArray: UserTC.getResolver('pushToArray')})
488+
schemaComposer.Mutation.addFields({userPushToArray: UserTC.getResolver('pushToArray')})
466489
```
467490

468491
`User` is the corresponding Mongoose model. If you do not wish to allow duplicates in the array then replace `$push` with `$addToSet`. Read the graphql-compose docs on custom resolvers for more info: https://graphql-compose.github.io/docs/en/basics-resolvers.html
469492

470493
NB if you set `unique: true` on the array then using the `update` `$push` approach will not check for duplicates, this is due to a MongoDB bug: https://jira.mongodb.org/browse/SERVER-1068. For more usage examples with `$push` and arrays see the MongoDB docs here https://docs.mongodb.com/manual/reference/operator/update/push/. Also note that `$push` will preserve order in the array (append to end of array) whereas `$addToSet` will not.
471494

472-
473495
## Customization options
474496

475497
When we convert model `const UserTC = composeWithMongoose(User, customizationOptions);` you may tune every piece of future derived types and resolvers.
476498

477499
### Here is flow typed definition of this options:
478500

479501
The top level of customization options. Here you setup name and description for the main type, remove fields or leave only desired fields.
502+
480503
```js
481504
export type typeConverterOpts = {
482505
name?: string,
@@ -491,6 +514,7 @@ export type typeConverterOpts = {
491514
```
492515

493516
This is `opts.inputType` level of options for default InputTypeObject which will be provided to all resolvers for `filter` and `input` args.
517+
494518
```js
495519
export type typeConverterInputTypeOpts = {
496520
name?: string,
@@ -506,6 +530,7 @@ export type typeConverterInputTypeOpts = {
506530
This is `opts.resolvers` level of options.
507531
If you set the option to `false` it will disable resolver or some of its input args.
508532
Every resolver's arg has it own options. They described below.
533+
509534
```js
510535
export type typeConverterResolversOpts = {
511536
findById?: false,
@@ -571,6 +596,7 @@ export type typeConverterResolversOpts = {
571596
This is `opts.resolvers.[resolverName].[filter|sort|record|limit]` level of options.
572597
You may tune every resolver's args independently as you wish.
573598
Here you may setup every argument and override some fields from the default input object type, described above in `opts.inputType`.
599+
574600
```js
575601
export type filterHelperArgsOpts = {
576602
filterTypeName?: string, // type name for `filter`
@@ -604,16 +630,20 @@ export type limitHelperArgsOpts = {
604630
## Used plugins
605631

606632
### [graphql-compose-connection](https://github.com/graphql-compose/graphql-compose-connection)
633+
607634
This plugin adds `connection` resolver. Build in mechanism allows sort by any unique indexes (not only by id). Also supported compound sorting (by several fields).
608635

609636
Besides standard connection arguments `first`, `last`, `before` and `after`, also added great arguments:
610-
* `filter` arg - for filtering records
611-
* `sort` arg - for sorting records
637+
638+
- `filter` arg - for filtering records
639+
- `sort` arg - for sorting records
612640

613641
This plugin completely follows to [Relay Cursor Connections Specification](https://facebook.github.io/relay/graphql/connections.htm).
614642

615643
### [graphql-compose-pagination](https://github.com/graphql-compose/graphql-compose-pagination)
644+
616645
This plugin adds `pagination` resolver.
617646

618647
## License
648+
619649
[MIT](https://github.com/graphql-compose/graphql-compose-mongoose/blob/master/LICENSE.md)

package.json

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"name": "graphql-compose-mongoose",
33
"version": "0.0.0-semantically-released",
44
"description": "Plugin for `graphql-compose` which derive a graphql types from a mongoose model.",
5+
"license": "MIT",
56
"files": [
67
"lib",
78
"node8",
@@ -22,7 +23,6 @@
2223
"mongoose",
2324
"mongodb"
2425
],
25-
"license": "MIT",
2626
"bugs": {
2727
"url": "https://github.com/graphql-compose/graphql-compose-mongoose/issues"
2828
},
@@ -31,11 +31,11 @@
3131
"object-path": "^0.11.4"
3232
},
3333
"optionalDependencies": {
34-
"graphql-compose-connection": ">=4.0.0",
35-
"graphql-compose-pagination": ">=4.0.0"
34+
"graphql-compose-connection": ">=5.0.0",
35+
"graphql-compose-pagination": ">=5.0.0"
3636
},
3737
"peerDependencies": {
38-
"graphql-compose": ">=5.0.2 || >=4.7.1",
38+
"graphql-compose": ">=6.0.0",
3939
"mongoose": ">=5.0.0 || >=4.4.0"
4040
},
4141
"devDependencies": {
@@ -51,27 +51,27 @@
5151
"@types/mongoose": "5.2.10",
5252
"babel-core": "^7.0.0-bridge.0",
5353
"babel-eslint": "^10.0.1",
54-
"babel-jest": "^24.3.1",
54+
"babel-jest": "^24.5.0",
5555
"cz-conventional-changelog": "^2.1.0",
56-
"eslint": "^5.15.1",
56+
"eslint": "^5.15.2",
5757
"eslint-config-airbnb-base": "^13.1.0",
5858
"eslint-config-prettier": "^4.1.0",
5959
"eslint-plugin-flowtype": "^3.4.2",
6060
"eslint-plugin-import": "^2.16.0",
6161
"eslint-plugin-prettier": "^3.0.1",
62-
"flow-bin": "^0.94.0",
62+
"flow-bin": "^0.95.1",
6363
"graphql": "14.1.1",
64-
"graphql-compose": "^5.11.0",
65-
"graphql-compose-connection": ">=4.0.0",
66-
"graphql-compose-pagination": ">=4.0.0",
67-
"jest": "^24.3.1",
68-
"mongodb-memory-server": "^4.0.1",
69-
"mongoose": "^5.4.18",
64+
"graphql-compose": "^6.0.1",
65+
"graphql-compose-connection": ">=5.0.0",
66+
"graphql-compose-pagination": ">=5.0.0",
67+
"jest": "^24.5.0",
68+
"mongodb-memory-server": "^4.2.1",
69+
"mongoose": "^5.4.19",
7070
"prettier": "^1.16.4",
7171
"request": "^2.88.0",
7272
"rimraf": "^2.6.3",
7373
"semantic-release": "^15.13.3",
74-
"tslint": "^5.13.1",
74+
"tslint": "^5.14.0",
7575
"tslint-config-prettier": "^1.18.0",
7676
"tslint-plugin-prettier": "^2.0.1",
7777
"typescript": "^3.3.3333"
@@ -98,8 +98,8 @@
9898
"tscheck": "tsc --noEmit",
9999
"flow": "./node_modules/.bin/flow",
100100
"test": "npm run coverage && npm run lint && npm run flow && npm run tscheck",
101-
"link": "yarn build && yarn link graphql-compose && yarn link graphql-compose-connection && yarn link mongoose && yarn link",
102-
"unlink": "yarn unlink graphql-compose && yarn unlink graphql-compose-connection && yarn unlink mongoose && yarn add graphql-compose graphql-compose-connection mongoose --dev",
101+
"link": "yarn build && yarn link graphql-compose && yarn link graphql-compose-connection && yarn link graphql-compose-pagination && yarn link mongoose && yarn link",
102+
"unlink": "rimraf node_modules && yarn install",
103103
"semantic-release": "semantic-release"
104104
}
105105
}

0 commit comments

Comments
 (0)