Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async prepare(options: Object = {}): Promise {
if (this.handler) {
return this.handler;
}
await this.init();
// Used for configuring, eg. entity layer, services, graphql or some other internal config parameter.
await this.__processHooks("configure");
// Once everything was configured and optionally installed, initialization of each app starts.
await this.__processHooks("preInit");
await this.__processHooks("init");
await this.__processHooks("postInit");
this.namespace = cls.createNamespace(Date.now().toString());
// Build event handler
const handler = createHandler(this.namespace, options);
this.handler = async args => {
this.__processHooks("preHandle");
const output = await handler(args);
this.__processHooks("postHandle");
return output;
};
return this.handler;
}
public async initAppElements() {
this.expressApp = express();
this.server = http.createServer(this.expressApp);
const io = socketIO(this.server);
const namespace = cls.createNamespace('sequelize-namespace');
(Sequelize as any).__proto__.useCLS(namespace);
const sequelize = new Sequelize({
// logging(msg) {
// (require('fs')).appendFileSync(`${__dirname}/../sequelize.log`, msg+"\n");
// },
database: this.appConfig.db.database,
dialect : 'postgres',
host : this.appConfig.db.host,
logging : false,
password: this.appConfig.db.password,
pool : {
idle: this.appConfig.db.poolIdleTimeout,
max : this.appConfig.db.poolSize,
},
constructor (connectOptions) {
this.connectOptions = Object.assign({user: connectOptions.username}, connectOptions)
const mysql = require('mysql2')
// filter connect options
this.dbDrive = mysql.createPool(this.connectOptions.reject(['username', 'dialect', 'logger', 'autoMigrate', 'development', 'production', 'test'])).promise()
this.tableInfo = {}
this.ns = createNamespace(`snake-orm-auto-transaction-for-mysql:${connectOptions.database}`)
}
/**
* @module botbuilder-applicationinsights
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import * as appInsights from 'applicationinsights';
import { Activity, BotTelemetryClient, TelemetryDependency, TelemetryEvent, TelemetryException, TelemetryTrace } from 'botbuilder-core';
import * as cls from 'cls-hooked';
const ns: any = cls.createNamespace('my.request');
// This is the currently recommended work-around for using Application Insights with async/await
// https://github.com/Microsoft/ApplicationInsights-node.js/issues/296
// This allows AppInsights to automatically apply the appropriate context objects deep inside the async/await chain.
// tslint:disable-next-line:no-submodule-imports
import { CorrelationContext, CorrelationContextManager } from 'applicationinsights/out/AutoCollection/CorrelationContextManager';
const origGetCurrentContext: any = CorrelationContextManager.getCurrentContext;
function getCurrentContext(): any {
// tslint:disable-next-line:no-backbone-get-set-outside-model
return ns.get('ctx') || origGetCurrentContext();
}
// Overwrite the built-in getCurrentContext() method with a new one.
CorrelationContextManager.getCurrentContext = getCurrentContext;
return new Promise(resolve => {
const session = getNamespace('webiny-api');
const req = session.get('req');
const token = req.get('Webiny-Authorization');
if (!token) {
resolve(null);
}
jwt.verify(token, this.config.jwtSecret, (err, decoded) => {
if (err) {
// TODO: check if token is expired
resolve(null);
} else {
this.config.entity.findById(decoded.id).then(user => {
this.user = user;
resolve(user);
}).catch(e => {
import { MysqlTransaction } from "./mysqltransaction";
import { SequelizeTransaction } from "./sequelizetransaction";
import { Transaction } from "./transaction";
import { DBManager } from "./dbmanager";
import { Transaction as SeqTransaction } from "sequelize";
import { OracleTransaction } from "./oracletransaction";
import { App } from "../tools/application";
import { MssqlTransaction } from "./mssqltransaction";
import { TypeormTransaction } from "./typeormtransaction";
class TransactionManager{
static transactionMap:Map = new Map(); //transaction map
static transactionMdl:string; //transaction 实例名
static expressions:Array; //纳入事务的过滤串
static namespace:any = require('cls-hooked')
.createNamespace('NOOMI_TX_NAMESPACE'); //cls namespace
static transactionId:number=1; //transaction id;
static pointcutId:string = 'NOOMI_TX_POINTCUT'; //切点名
static addToAopExpressions:Array = []; //待添加到transaction aop的表达式串
static isolationLevel:number=0; //隔离级 1read uncommited 2read commited 3repeatable read 4serializable
static transactionOption:any; //事务配置项
static init(cfg:any){
//transaction 模块实例名
this.transactionMdl = cfg.transaction||'noomi_transaction';
//隔离级
if(cfg.isolation_level && typeof cfg.isolation_level === 'number'){
this.isolationLevel = cfg.isolation_level;
}
//添加Aspect
let adviceInstance = InstanceFactory.addInstance({
name:'NoomiTransactionAdvice', //实例名
public create(cb) {
createNamespace(ContextTypes.ROOT).run(cb);
}
'use strict';
const cls = require('cls-hooked');
const uuid = require('uuid');
const ns = cls.createNamespace('d7519f70-1ccf-11e8-accf-0ed5f89f718b');
const key = 'CORRELATOR';
const getId = () => ns.get(key);
const correlator = (header = 'x-correlation-id') => handler => (req, res, ...restArgs) => {
req.correlationId = getId;
return ns.runAndReturn(() => {
const id = req.headers[header] || uuid.v4();
ns.set(key, id);
return handler(req, res, ...restArgs);
});
};
module.exports = {
correlator,
'use strict';
const cls = require('cls-hooked');
const nsid = 'a6a29a6f-6747-4b5f-b99f-07ee96e32f88';
const ns = cls.createNamespace(nsid);
/** Express.js middleware that is responsible for initializing the context for each request. */
function middleware(req, res, next) {
ns.run(() => next());
}
/**
* Gets a value from the context by key. Will return undefined if the context has not yet been initialized for this request or if a value is not found for the specified key.
* @param {string} key
*/
function get(key) {
if (ns && ns.active) {
return ns.get(key);
}
}
return function postgres(next) {
const pool = new Pool(
...(url
? [
{
connectionString: url
}
]
: [])
);
const namespace = createNamespace('postgres');
orm.setConnection(async () => {
const connector = namespace.get('getConnection');
if (typeof connector !== 'function') {
throw new Error(
'Accessing postgres outside the context of a request? UNACCEPTABLE'
);
}
const connection = await connector();
return {
connection,
release() {}
};
});
return async function inner(context) {