Skip to content

Commit

Permalink
added conditional fields, changed mocha tests to jest
Browse files Browse the repository at this point in the history
  • Loading branch information
du5rte committed May 9, 2018
1 parent 04b9048 commit d855eea
Show file tree
Hide file tree
Showing 11 changed files with 8,504 additions and 49 deletions.
3 changes: 1 addition & 2 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"presets": [
"es2015-node5",
"stage-3"
"env"
],
"plugins": [
"transform-object-rest-spread",
Expand Down
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ $ npm install --save-dev graphql-mongodb-projection
Just add it has a second parameter in a `.findOne` inside the `resolve` function, make sure to pass it `info`. (example using `koa` with `express` is the 3rd parameter).

```js
import infoToProjection from 'graphql-mongodb-projection'
import graphqlMongodbProjection from 'graphql-mongodb-projection'

const user = {
type: UserType,
Expand All @@ -35,11 +35,25 @@ const user = {
_id: {type: new GraphQLNonNull(GraphQLString)},
},
resolve(root, args, ctx, info) {
return db.collection('users').findOne({_id: ObjectId(args._id)}, infoToProjection(info))
return db.collection('users').findOne({_id: ObjectId(args._id)}, graphqlMongodbProjection(info))
}
}
```

## Conditional fields

```js
resolve(root, args, ctx, info) {
const projection = graphqlMongodbProjection(info, {
// if asked for `avatar` will project `profile.avatar`
'avatar': 'profile.avatar',
// always return `verified`
'verified': true
})
}

```


on `GraphiQL`
```
Expand Down Expand Up @@ -150,3 +164,6 @@ Result
}
}
```

## TODO
- create a temporary mongoDB service
4 changes: 2 additions & 2 deletions example/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {

import { db, ObjectId } from 'mongodb'

import infoToProjection from '../src'
import graphqlMongodbProjection from '../src'

const UserType = new GraphQLObjectType({
name: 'User',
Expand All @@ -31,7 +31,7 @@ const user = {
},
resolve(root, { _id }, ctx, info) {
// HERE ->
return db.collection('users').findOne({_id: ObjectId(_id)}, infoToProjection(info))
return db.collection('users').findOne({_id: ObjectId(_id)}, graphqlMongodbProjection(info))
}
}

Expand Down
78 changes: 69 additions & 9 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,50 @@ Object.defineProperty(exports, "__esModule", {
value: true
});

var _entries = require('babel-runtime/core-js/object/entries');

var _entries2 = _interopRequireDefault(_entries);

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.default = infoToProjection;
exports.infoToProjection = infoToProjection;
exports.conditionsToProjection = conditionsToProjection;
exports.graphqlMongodbProjection = graphqlMongodbProjection;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var isBoolean = function isBoolean(val) {
return typeof val === 'boolean';
};
var isString = function isString(val) {
return typeof val === 'string';
};

function infoToProjection(info) {
let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (info.fieldASTs || info.fieldNodes)[0];
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (info.fieldASTs || info.fieldNodes)[0];

return context.selectionSet.selections.reduce((projection, selection) => {
return context.selectionSet.selections.reduce(function (projection, selection) {
switch (selection.kind) {
case 'Field':

let nodeSelection = undefined;
var nodeSelection = undefined;

if (selection && selection.selectionSet && selection.selectionSet.selections) {
nodeSelection = selection.selectionSet.selections.find(sel => sel.name.value === 'node');
nodeSelection = selection.selectionSet.selections.find(function (sel) {
return sel.name && sel.name.value && sel.name.value === 'node';
});
}

if (selection.name.value === 'edges' && typeof nodeSelection !== 'undefined') {
return _extends({}, projection, infoToProjection(info, nodeSelection));
} else {
return _extends({}, projection, {
[selection.name.value]: true
});
return _extends({}, projection, _defineProperty({}, selection.name.value, true));
}

// TODO: to test, not sure what they are
Expand All @@ -41,4 +63,42 @@ function infoToProjection(info) {
return {};
}
}, {});
}
}

function conditionsToProjection(_projection, conditions) {
return (0, _entries2.default)(conditions).reduce(function (projection, _ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];

// if value is Boolean add to projection
if (isBoolean(value)) {
return _extends({}, projection, _defineProperty({}, key, value));
}

// if value is String and exists in _projection replace it with value
// https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd
else if (isString(value) && projection.hasOwnProperty(key)) {
var _Key = projection[key],
rest = _objectWithoutProperties(projection, [key]);

return _extends({}, rest, _defineProperty({}, value, true));
} else {
return projection;
}
}, _projection);
}

function graphqlMongodbProjection(info, conditions) {
var infoProjection = infoToProjection(info);

if (conditions) {
var conditionaProjection = conditionsToProjection(infoProjection, conditions);

return conditionaProjection;
}

return infoProjection;
}

exports.default = graphqlMongodbProjection;
Loading

0 comments on commit d855eea

Please sign in to comment.