graphql-compose-mongoose
Version:
Plugin for `graphql-compose` which derive a graphql types from a mongoose model.
67 lines • 2.9 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateDoc = validateDoc;
exports.validateAndThrow = validateAndThrow;
exports.validateManyAndThrow = validateManyAndThrow;
const mongoose_1 = require("mongoose");
const errors_1 = require("../../errors");
const versionNumber = Number(mongoose_1.version.charAt(0));
function validateDoc(doc) {
return __awaiter(this, void 0, void 0, function* () {
const validations = versionNumber >= 7
? doc.validateSync()
: yield new Promise((resolve) => doc.validate(resolve));
return (validations === null || validations === void 0 ? void 0 : validations.errors)
? {
message: validations.message,
errors: Object.keys(validations.errors).map((key) => {
const { message, value } = validations.errors[key];
return {
path: key,
message,
value,
};
}),
}
: null;
});
}
function validateAndThrow(doc) {
return __awaiter(this, void 0, void 0, function* () {
const validations = yield validateDoc(doc);
if (validations) {
throw new errors_1.ValidationError(validations);
}
});
}
function validateManyAndThrow(docs) {
return __awaiter(this, void 0, void 0, function* () {
const combinedValidators = [];
let hasValidationError = false;
for (let idx = 0; idx < docs.length; idx++) {
const validations = yield validateDoc(docs[idx]);
if (validations) {
validations.errors.forEach((validatorError) => {
combinedValidators.push(Object.assign(Object.assign({}, validatorError), { idx }));
});
hasValidationError = true;
}
}
if (hasValidationError) {
throw new errors_1.ValidationError({
message: 'Nothing has been saved. Some documents contain validation errors',
errors: combinedValidators,
});
}
});
}
//# sourceMappingURL=validate.js.map