Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update queryParser to access a listAdapter #1713

Merged
merged 1 commit into from
Oct 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/plenty-owls-vanish/changes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"releases": [{ "name": "@keystone-alpha/mongo-join-builder", "type": "major" }],
"dependents": [
{
"name": "@keystone-alpha/adapter-mongoose",
"type": "patch",
"dependencies": ["@keystone-alpha/mongo-join-builder"]
}
]
}
1 change: 1 addition & 0 deletions .changeset/plenty-owls-vanish/changes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Update queryParser to access a `{ listAdapter }` rather than a `{ tokenizer }`. This means that `{ simpleTokenizer, relationshipTokenizer, getRelatedListAdapterFromQueryPathFactory}` do not need to be exported from `mongo-join-builder`.
19 changes: 1 addition & 18 deletions packages/adapter-mongoose/lib/adapter-mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ const {
BaseFieldAdapter,
} = require('@keystone-alpha/keystone');
const {
simpleTokenizer,
relationshipTokenizer,
getRelatedListAdapterFromQueryPathFactory,
queryParser,
pipelineBuilder,
mutationBuilder,
Expand Down Expand Up @@ -122,21 +119,7 @@ class MongooseListAdapter extends BaseListAdapter {
this.model = null;

this.queryBuilder = async (query, aggregate) => {
const queryTree = queryParser(
{
tokenizer: {
// executed for simple query components (eg; 'fulfilled: false' / name: 'a')
simple: simpleTokenizer({
getRelatedListAdapterFromQueryPath: getRelatedListAdapterFromQueryPathFactory(this),
}),
// executed for complex query components (eg; items: { ... })
relationship: relationshipTokenizer({
getRelatedListAdapterFromQueryPath: getRelatedListAdapterFromQueryPathFactory(this),
}),
},
},
query
);
const queryTree = queryParser({ listAdapter: this }, query);
const pipeline = pipelineBuilder(queryTree);
const postQueryMutations = mutationBuilder(queryTree.relationships);
// Run the query against the given database and collection
Expand Down
62 changes: 4 additions & 58 deletions packages/mongo-join-builder/examples/nested-relationship/index.js
Original file line number Diff line number Diff line change
@@ -1,62 +1,8 @@
const omitBy = require('lodash.omitby');

const { queryParser, pipelineBuilder, mutationBuilder } = require('../../');
const getDatabase = require('../database');

const builder = async (query, aggregate) => {
const queryTree = queryParser(
{
tokenizer: {
// executed for simple query components (eg; 'fulfilled: false' / name: 'a')
// eslint-disable-next-line no-unused-vars
simple: (query, key, path) => [{ [key]: { $eq: query[key] } }],

// executed for complex query components (eg; items: { ... })
relationship: (query, key, path, uid) => {
const [field, filter] = key.split('_');

const fieldToTableMap = {
items: 'items',
stock: 'warehouses',
};

return {
from: fieldToTableMap[field], // the collection name to join with
field: field, // The field on the 'orders' collection
// A mutation to run on the data post-join. Useful for merging joined
// data back into the original object.
// Executed on a depth-first basis for nested relationships.
// eslint-disable-next-line no-unused-vars
postQueryMutation: (parentObj, keyOfRelationship, rootObj, pathToParent) => {
// For this example, we want the joined items to overwrite the array
//of IDs
return omitBy(
{
...parentObj,
[field]: parentObj[keyOfRelationship],
},
// Clean up the result to remove the intermediate results
(_, keyToOmit) => keyToOmit.startsWith(uid)
);
},
// The conditions under which an item from the 'orders' collection is
// considered a match and included in the end result
// All the keys on an 'order' are available, plus 3 special keys:
// 1) <uid>_<field>_every - is `true` when every joined item matches the
// query
// 2) <uid>_<field>_some - is `true` when some joined item matches the
// query
// 3) <uid>_<field>_none - is `true` when none of the joined items match
// the query
matchTerm: { [`${uid}_${field}_${filter}`]: true },
// Flag this is a to-many relationship
many: true,
};
},
},
},
query
);
const builder = async (query, aggregate, listAdapter) => {
const queryTree = queryParser({ listAdapter }, query);
const pipeline = pipelineBuilder(queryTree);
const postQueryMutations = mutationBuilder(queryTree.relationships);
// Run the query against the given database and collection
Expand All @@ -79,9 +25,9 @@ const query = {

(async () => {
const database = await getDatabase();

const listAdapter = {};
try {
const result = await builder(query, getAggregate(database, 'orders'));
const result = await builder(query, getAggregate(database, 'orders'), listAdapter);
console.log('orders:', prettyPrintResults(result));
} catch (error) {
console.error(error);
Expand Down
75 changes: 4 additions & 71 deletions packages/mongo-join-builder/examples/relationship/index.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,7 @@
const omitBy = require('lodash.omitby');

const { queryParser, pipelineBuilder, mutationBuilder } = require('../../');
const getDatabase = require('../database');
const builder = async (query, aggregate) => {
const queryTree = queryParser(
{
tokenizer: {
// executed for simple query components (eg; 'fulfilled: false' / name: 'a')
simple: (query, key, path) => {
if (path[0] === 'fulfilled') {
return [
{
// for the fulfilled clause, we want a direct equality check
[key]: { $eq: query[key] },
},
];
} else {
return [
{
// in this example, we want an 'in' check, so we use a regex
[key]: { $regex: new RegExp(query[key]) },
},
];
}
},

// executed for complex query components (eg; items: { ... })
relationship: (query, key, path, uid) => {
const fieldToTableMap = {
items: 'items',
stock: 'warehouses',
};

return {
from: fieldToTableMap[key], // the collection name to join with
field: key, // The field on the 'orders' collection
// A mutation to run on the data post-join. Useful for merging joined
// data back into the original object.
// Executed on a depth-first basis for nested relationships.
// eslint-disable-next-line no-unused-vars
postQueryMutation: (parentObj, keyOfRelationship, rootObj, pathToParent) => {
// For this example, we want the joined items to overwrite the array
//of IDs
return omitBy(
{
...parentObj,
[key]: parentObj[keyOfRelationship],
},
// Clean up the result to remove the intermediate results
(_, keyToOmit) => keyToOmit.startsWith(uid)
);
},
// The conditions under which an item from the 'orders' collection is
// considered a match and included in the end result
// All the keys on an 'order' are available, plus 3 special keys:
// 1) <uid>_<field>_every - is `true` when every joined item matches the
// query
// 2) <uid>_<field>_some - is `true` when some joined item matches the
// query
// 3) <uid>_<field>_none - is `true` when none of the joined items match
// the query
matchTerm: { [`${uid}_${key}_every`]: true },
// Flag this is a to-many relationship
many: true,
};
},
},
},
query
);
const builder = async (query, aggregate, listAdapter) => {
const queryTree = queryParser({ listAdapter }, query);
const pipeline = pipelineBuilder(queryTree);
const postQueryMutations = mutationBuilder(queryTree.relationships);
// Run the query against the given database and collection
Expand All @@ -85,9 +18,9 @@ const query = {

(async () => {
const database = await getDatabase();

const listAdapter = {};
try {
const result = await builder(query, getAggregate(database, 'orders'));
const result = await builder(query, getAggregate(database, 'orders'), listAdapter);
console.log('orders:', prettyPrintResults(result));
} catch (error) {
console.error(error);
Expand Down
6 changes: 0 additions & 6 deletions packages/mongo-join-builder/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
const { simpleTokenizer } = require('./lib/tokenizers/simple');
const { relationshipTokenizer } = require('./lib/tokenizers/relationship');
const { getRelatedListAdapterFromQueryPathFactory } = require('./lib/tokenizers/relationship-path');
const { queryParser } = require('./lib/query-parser');
const { pipelineBuilder, mutationBuilder } = require('./lib/join-builder');

module.exports = {
simpleTokenizer,
relationshipTokenizer,
getRelatedListAdapterFromQueryPathFactory,
queryParser,
pipelineBuilder,
mutationBuilder,
Expand Down
25 changes: 18 additions & 7 deletions packages/mongo-join-builder/lib/query-parser.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const cuid = require('cuid');
const { getType, flatten, objMerge } = require('@keystone-alpha/utils');

const { simpleTokenizer } = require('./tokenizers/simple');
const { relationshipTokenizer } = require('./tokenizers/relationship');
const { getRelatedListAdapterFromQueryPathFactory } = require('./tokenizers/relationship-path');

// If it's 0 or 1 items, we can use it as-is. Any more needs an $and/$or
const joinTerms = (matchTerms, joinOp) =>
matchTerms.length > 1 ? { [joinOp]: matchTerms } : matchTerms[0];
Expand All @@ -11,7 +15,9 @@ const flattenQueries = (parsedQueries, joinOp) => ({
relationships: objMerge(parsedQueries.map(q => q.relationships)),
});

function parser({ tokenizer, getUID = cuid }, query, pathSoFar = []) {
function parser({ listAdapter, getUID = cuid }, query, pathSoFar = []) {
const getRelatedListAdapterFromQueryPath = getRelatedListAdapterFromQueryPathFactory(listAdapter);

if (getType(query) !== 'Object') {
throw new Error(
`Expected an Object for query, got ${getType(query)} at path ${pathSoFar.join('.')}`
Expand All @@ -23,31 +29,36 @@ function parser({ tokenizer, getUID = cuid }, query, pathSoFar = []) {
if (['AND', 'OR'].includes(key)) {
// An AND/OR query component
return flattenQueries(
value.map((_query, index) => parser({ tokenizer, getUID }, _query, [...path, index])),
value.map((_query, index) => parser({ listAdapter, getUID }, _query, [...path, index])),
{ AND: '$and', OR: '$or' }[key]
);
} else if (getType(value) === 'Object') {
// A relationship query component
const uid = getUID(key);
const queryAst = tokenizer.relationship(query, key, path, uid);
const queryAst = relationshipTokenizer({ getRelatedListAdapterFromQueryPath })(
query,
key,
path,
uid
);
if (getType(queryAst) !== 'Object') {
throw new Error(
`Must return an Object from 'tokenizer.relationship' function, given ${path.join('.')}`
`Must return an Object from 'relationshipTokenizer' function, given ${path.join('.')}`
);
}
return {
// queryAst.matchTerm is our filtering expression. This determines if the
// parent item is included in the final list
matchTerm: queryAst.matchTerm,
postJoinPipeline: [],
relationships: { [uid]: { ...queryAst, ...parser({ tokenizer, getUID }, value, path) } },
relationships: { [uid]: { ...queryAst, ...parser({ listAdapter, getUID }, value, path) } },
};
} else {
// A simple field query component
const queryAst = tokenizer.simple(query, key, path);
const queryAst = simpleTokenizer({ getRelatedListAdapterFromQueryPath })(query, key, path);
if (getType(queryAst) !== 'Object') {
throw new Error(
`Must return an Object from 'tokenizer.simple' function, given ${path.join('.')}`
`Must return an Object from 'simpleTokenizer' function, given ${path.join('.')}`
);
}
return {
Expand Down
Loading