graphql-anywhere-mongodb-express
Version:
express middleware that accepts graphql requests and runs them as mongo queries
35 lines • 1.72 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const graphql_anywhere_mongodb_1 = require("graphql-anywhere-mongodb");
const handle_async_1 = require("../handle-async");
function connectToMongoMiddleware(options) {
// Setup options
const mongoUri = options.uri || options.url;
const connection = options.connection;
let client = null;
// Error if both connection and URI or neither are specified
if ([mongoUri, connection].filter(x => !!x).length !== 1) {
throw new Error('Can only specify one of either uri/url or connection');
}
return handle_async_1.handleAsync((req, res, next) => tslib_1.__awaiter(this, void 0, void 0, function* () {
req['__mongoGraphQLClient'] = client || (client = yield acquireClient(mongoUri, connection, options, options.mongoClientOptions));
next();
}));
}
exports.connectToMongoMiddleware = connectToMongoMiddleware;
function acquireClient(mongoUri, connection, options, clientOptions) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
// Connect to URI directly
if (mongoUri) {
return yield graphql_anywhere_mongodb_1.default.forUri(mongoUri, Object.assign({}, clientOptions, options));
}
// Use pre existing client
if (connection) {
return graphql_anywhere_mongodb_1.default.forConnection(connection, options);
}
// Could not acquire connection, fail the request
throw new Error(`GraphQL MongoDB middleware could not find a way to connect to MongoDB. Please ensure you pass the right options.`);
});
}
//# sourceMappingURL=connection-middleware.js.map