UNPKG

koa-neo4j

Version:

Rapidly create REST APIs, powered by Koa and Neo4j -- batteries included with built-in role based authentication via JWT and reusable backend components

122 lines (103 loc) 5.53 kB
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.API = exports.Procedure = exports.Neo4jConnection = undefined;var _neo4jDriver = require('neo4j-driver');var _neo4jDriver2 = _interopRequireDefault(_neo4jDriver); var _fs = require('fs');var _fs2 = _interopRequireDefault(_fs); var _path = require('path');var _path2 = _interopRequireDefault(_path); var _chai = require('chai');var _chai2 = _interopRequireDefault(_chai); var _chalk = require('chalk');var _chalk2 = _interopRequireDefault(_chalk); var _parseNeo4j = require('parse-neo4j'); var _procedure = require('./procedure'); var _log4jsWrapperAdvanced = require('log4js-wrapper-advanced');var _log4jsWrapperAdvanced2 = _interopRequireDefault(_log4jsWrapperAdvanced);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} const logger = _log4jsWrapperAdvanced2.default.getLogger(); class Neo4jConnection { constructor({ url, user, password } = {}) { this.queries = {}; this.driver = _neo4jDriver2.default.driver(url, _neo4jDriver2.default.auth.basic(user, password)); const session = this.driver.session(); this.initialized = session.run('RETURN "Neo4j instance successfully connected."'). then(result => { logger.trace(_chalk2.default.green((0, _parseNeo4j.parse)(result))); session.close(); }). catch(error => { logger.error( _chalk2.default.red('Error connecting to the Neo4j instance, check connection options')); logger.error(error); throw error; }); } addCypherQueryFile(cypherQueryFilePath) { this.queries[cypherQueryFilePath] = _fs2.default.readFileSync(cypherQueryFilePath, 'utf8'); } async executeCypher(cypherQueryOrQueryFilePath, queryParams, pathIsQuery = false, ctx) { const _executeCypher = async (query, queryParams, ctx) => { let result, session, tx; try { session = ctx && ctx._neo4j_session || this.driver.session(); logger.trace( _chalk2.default.green(JSON.stringify({ query: query, params: queryParams }, null, '\t'))); if (ctx && ctx.globalTransaction) { tx = ctx._neo4j_tx || session.beginTransaction(); result = await tx.run(query, queryParams).then(_parseNeo4j.parse); } else { result = await session.run(query, queryParams).then(_parseNeo4j.parse); await session.close(); } } catch (error) { await session.close(); const errorDesc = error.fields ? JSON.stringify(error.fields[0]) : String(error); throw new Error(`error while executing Cypher:${errorDesc}`); } return result; }; const _executeCyphers = async (query, queryParams, ctx) => { let session, tx; const results = []; try { session = ctx && ctx._neo4j_session || this.driver.session(); tx = ctx && ctx._neo4j_tx || session.beginTransaction(); logger.trace( _chalk2.default.green(JSON.stringify({ query: query, params: queryParams }, null, '\t'))); if (ctx && ctx.globalTransaction) for (const entry of query) results.push((await tx.run(entry, queryParams).then(_parseNeo4j.parse)));else { for (const entry of query) results.push((await tx.run(entry, queryParams).then(_parseNeo4j.parse))); await tx.commit(); await session.close(); } } catch (error) { await session.close(); const errorDesc = error.fields ? JSON.stringify(error.fields[0]) : String(error); throw new Error(`error while executing Cypher:${errorDesc}`); } return results; }; if (!pathIsQuery) { cypherQueryOrQueryFilePath = _path2.default.resolve(process.cwd(), cypherQueryOrQueryFilePath); if (!this.queries[cypherQueryOrQueryFilePath]) this.addCypherQueryFile(cypherQueryOrQueryFilePath); } const query = pathIsQuery ? cypherQueryOrQueryFilePath : this.queries[cypherQueryOrQueryFilePath]; let result = []; if (Array.isArray(query) && query.length) result = await _executeCyphers(query, queryParams, ctx);else result = await _executeCypher(query, queryParams, ctx); return result; }} class API { constructor(neo4jConnection, options) { if (typeof options.procedure === 'function') this.invoke = options.procedure;else this.invoke = (0, _procedure.createProcedure)(neo4jConnection, options); _chai2.default.assert.typeOf(options.method, 'string'); _chai2.default.assert.typeOf(options.route, 'string'); this.method = options.method; this.route = options.route; this.allowedRoles = options.allowedRoles || []; _chai2.default.assert.isArray(this.allowedRoles); this.allowedRoles = this.allowedRoles.map(role => role.toLowerCase()); this.requiresJwtAuthentication = this.allowedRoles.length > 0; }}exports. Neo4jConnection = Neo4jConnection;exports.Procedure = _procedure.Procedure;exports.API = API;