Skip to content

Commit

Permalink
Merge branch 'feature/dbHelpers'
Browse files Browse the repository at this point in the history
  • Loading branch information
arackaf committed Jan 27, 2018
2 parents f2d3cae + b37209b commit 1d99aa2
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 44 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mongo-graphql-starter",
"version": "0.6.1",
"version": "0.6.2",
"description": "",
"main": "index.js",
"repository": {
Expand Down
3 changes: 2 additions & 1 deletion src/codeGen/createTypeResolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ export default function createGraphqlResolver(objectToCreate) {
`import hooksObj from "../hooks";`,
`const { decontructGraphqlQuery, parseRequestedFields, getMongoProjection, newObjectFromArgs, getUpdateObject } = queryUtilities;`,
`import { ObjectId } from "mongodb";`,
`import ${objectToCreate.__name} from "./${objectToCreate.__name}";`
`import ${objectToCreate.__name} from "./${objectToCreate.__name}";`,
`import * as dbHelpers from "../dbHelpers";`
];
let typeImports = new Set([]);
let relationships = "";
Expand Down
54 changes: 54 additions & 0 deletions src/codeGen/dbHelpersTemplate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { MongoError } from "mongodb";

export async function runUpdate(db, table, $match, updates, options) {
if (updates.$set || updates.$inc || updates.$push || updates.$pull || updates.$addToSet) {
try {
await db.collection(table).update($match, updates, options);
} catch (err) {
if (err instanceof MongoError) {
throw `The following error was thrown by Mongo when attempting to perform this update: ${err.toString()}`;
} else {
throw err;
}
}
}
}

export async function runDelete(db, table, $match) {
try {
await db.collection(table).remove($match);
} catch (err) {
if (err instanceof MongoError) {
throw `The following error was thrown by Mongo when attempting to perform this deletion: ${err.toString()}`;
} else {
throw err;
}
}
}

export async function runInsert(db, table, newObject) {
try {
await db.collection(table).insert(newObject);
} catch (err) {
if (err instanceof MongoError) {
throw `The following error was thrown by Mongo when attempting to perform this insertion: ${err.toString()}`;
} else {
throw err;
}
}
}

export async function runQuery(db, table, aggregateItems) {
try {
return await db
.collection(table)
.aggregate(aggregateItems)
.toArray();
} catch (err) {
if (err instanceof MongoError) {
throw `The following error was thrown by Mongo when attempting to perform this query: ${err.toString()}`;
} else {
throw err;
}
}
}
39 changes: 11 additions & 28 deletions src/codeGen/resolverTemplate.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ export async function load${objName}s(db, queryPacket) {
$limit != null ? { $limit } : null
].filter(item => item);

let ${objName}s = await db
.collection("${table}")
.aggregate(aggregateItems)
.toArray();
let ${objName}s = await dbHelpers.runQuery(db, "${table}", aggregateItems);
${relationships}
await processHook(hooksObj, "${objName}", "adjustResults", ${objName}s);
return ${objName}s;
Expand Down Expand Up @@ -46,11 +43,7 @@ export default {
result.Meta = {};

if (queryPacket.metadataRequested.get("count")) {
let countResults = (await db
.collection("${table}")
.aggregate([{ $match: queryPacket.$match }, { $group: { _id: null, count: { $sum: 1 } } }])
.toArray());

let countResults = await dbHelpers.runQuery(db, "${table}", [{ $match: queryPacket.$match }, { $group: { _id: null, count: { $sum: 1 } } }]);
result.Meta.count = countResults.length ? countResults[0].count : 0;
}
}
Expand All @@ -68,7 +61,7 @@ export default {
if (await processHook(hooksObj, "${objName}", "beforeInsert", newObject, root, args, context, ast) === false) {
return { ${objName}: null };
}
await db.collection("${table}").insert(newObject);
await dbHelpers.runInsert(db, "${table}", newObject);
await processHook(hooksObj, "${objName}", "afterInsert", newObject, root, args, context, ast);

let result = (await load${objName}s(db, { $match: { _id: newObject._id }, $project, $limit: 1 }))[0];
Expand All @@ -84,13 +77,10 @@ export default {
let { $match, $project } = decontructGraphqlQuery({ _id: args._id }, ast, ${objName}, "${objName}");
let updates = getUpdateObject(args.Updates || {}, ${objName});

let res = await processHook(hooksObj, "${objName}", "beforeUpdate", $match, updates, root, args, context, ast);
if (res === false) {
if (await processHook(hooksObj, "${objName}", "beforeUpdate", $match, updates, root, args, context, ast) === false) {
return { ${objName}: null };
}
if (updates.$set || updates.$inc || updates.$push || updates.$pull || updates.$addToSet) {
await db.collection("${table}").update($match, updates);
}
await dbHelpers.runUpdate(db, "${table}", $match, updates);
await processHook(hooksObj, "${objName}", "afterUpdate", $match, updates, root, args, context, ast);

let result = $project ? (await load${objName}s(db, { $match, $project, $limit: 1 }))[0] : null;
Expand All @@ -104,13 +94,10 @@ export default {
let { $match, $project } = decontructGraphqlQuery({ _id_in: args._ids }, ast, ${objName}, "${objName}s");
let updates = getUpdateObject(args.Updates || {}, ${objName});

let res = await processHook(hooksObj, "${objName}", "beforeUpdate", $match, updates, root, args, context, ast);
if (res === false) {
if (await processHook(hooksObj, "${objName}", "beforeUpdate", $match, updates, root, args, context, ast) === false) {
return { success: true };
}
if (updates.$set || updates.$inc || updates.$push || updates.$pull || updates.$addToSet) {
await db.collection("${table}").update($match, updates, { multi: true });
}
await dbHelpers.runUpdate(db, "${table}", $match, updates, { multi: true });
await processHook(hooksObj, "${objName}", "afterUpdate", $match, updates, root, args, context, ast);

let result = $project ? await load${objName}s(db, { $match, $project }) : null;
Expand All @@ -124,13 +111,10 @@ export default {
let { $match } = decontructGraphqlQuery(args.Match, ast, ${objName});
let updates = getUpdateObject(args.Updates || {}, ${objName});

let res = await processHook(hooksObj, "${objName}", "beforeUpdate", $match, updates, root, args, context, ast);
if (res === false) {
if (await processHook(hooksObj, "${objName}", "beforeUpdate", $match, updates, root, args, context, ast) === false) {
return { success: true };
}
if (updates.$set || updates.$inc || updates.$push || updates.$pull || updates.$addToSet) {
await db.collection("${table}").update($match, updates, { multi: true });
}
await dbHelpers.runUpdate(db, "${table}", $match, updates, { multi: true });
await processHook(hooksObj, "${objName}", "afterUpdate", $match, updates, root, args, context, ast);

return { success: true };
Expand All @@ -142,11 +126,10 @@ export default {
let db = await root.db;
let $match = { _id: ObjectId(args._id) };

let res = await processHook(hooksObj, "${objName}", "beforeDelete", $match, root, args, context, ast);
if (res === false) {
if (await processHook(hooksObj, "${objName}", "beforeDelete", $match, root, args, context, ast) === false) {
return false;
}
await db.collection("${table}").remove($match);
await dbHelpers.runDelete(db, "${table}", $match);
await processHook(hooksObj, "${objName}", "afterDelete", $match, root, args, context, ast);
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/createGraphqlSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,11 @@ export default function(source, destPath) {
fs.readFileSync(path.resolve(__dirname, "./codeGen/processingHooksTemplate.js"), { encoding: "utf8" })
);
}
if (!fs.existsSync(path.join(rootDir, "dbHelpers.js"))) {
fs.writeFileSync(
path.join(rootDir, "dbHelpers.js"),
fs.readFileSync(path.resolve(__dirname, "./codeGen/dbHelpersTemplate.js"), { encoding: "utf8" })
);
}
});
}
36 changes: 22 additions & 14 deletions src/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,33 @@ export async function processHook(hooks, TypeName, hookName, ...args) {
let rootHooks = hooks.Root;
let typeHooks = hooks[TypeName];
if (rootHooks) {
if (typeof rootHooks === "function") {
rootHooks = new rootHooks();
}
if (rootHooks[hookName]) {
let res = await rootHooks[hookName](...args);
if (shortCircuitHooks.has(hookName) && res === false) {
return false;
try {
if (typeof rootHooks === "function") {
rootHooks = new rootHooks();
}
if (rootHooks[hookName]) {
let res = await rootHooks[hookName](...args);
if (shortCircuitHooks.has(hookName) && res === false) {
return false;
}
}
} catch (err) {
throw `The following error happened in root hook method ${hookName}: ${err.toString()}`;
}
}
if (typeHooks) {
if (typeof typeHooks === "function") {
typeHooks = new typeHooks();
}
if (typeHooks[hookName]) {
let res = await typeHooks[hookName](...args);
if (shortCircuitHooks.has(hookName) && res === false) {
return false;
try {
if (typeof typeHooks === "function") {
typeHooks = new typeHooks();
}
if (typeHooks[hookName]) {
let res = await typeHooks[hookName](...args);
if (shortCircuitHooks.has(hookName) && res === false) {
return false;
}
}
} catch (err) {
throw `The following error happened in hook method ${hookName} for type ${TypeName}: ${err.toString()}`;
}
}
}

0 comments on commit 1d99aa2

Please sign in to comment.