cube.js 上下文的一些说明
以前有大概介绍过上下文变量,以下重点介绍一个上下文的说明
USER_CONTEXT
此变量主要是基于cube.js 的安全模式进行抽象的,核心是基于express 的中间件模式扩展的一个
- 参考代码
protected async defaultCheckAuth(req: Request, auth?: string) {
if (auth) {
const secret = this.apiSecret;
try {
req.authInfo = jwt.verify(auth, secret);
} catch (e) {
if (this.enforceSecurityChecks) {
throw new UserError('Invalid token');
} else {
this.log({
type: 'Invalid Token',
token: auth,
error: e.stack || e.toString()
}, <any>req);
}
}
} else if (this.enforceSecurityChecks) {
throw new UserError('Authorization header isn\'t set');
}
}
COMPILE_CONTEXT
此上下文主要是关于schema编译的,早期版本比较简单,主要是基于express 的request 提取
认证信息,目前已经进行了扩展,支持了requestid 同时包含了一个extendContext (可以说是express 的中间件)
这样我们就可以更好的扩展schema 的处理了
- 参考代码
protected requestContextMiddleware: RequestHandler = async (req: Request, res: Response, next: NextFunction) => {
req.context = await this.contextByReq(req, req.authInfo, getRequestIdFromRequest(req));
if (next) {
next();
}
}
public async contextByReq(req, authInfo, requestId) {
const extensions = await Promise.resolve(typeof this.extendContext === 'function' ? this.extendContext(req) : {});
return {
authInfo,
requestId,
};
}
参考编译函数
cubejs-server-core server.ts 中对于编译函数的创建
public getCompilerApi(context: RequestContext) {
const appId = this.contextToAppId(context);
let compilerApi = this.compilerCache.get(appId);
const currentSchemaVersion = this.options.schemaVersion && (() => this.options.schemaVersion(context));
if (!compilerApi) {
compilerApi = this.createCompilerApi(
this.repositoryFactory(context), {
dbType: (dataSourceContext) => this.contextToDbType({
externalDbType: this.contextToExternalDbType(context),
dialectClass: (dialectContext) => this.options.dialectFactory &&
this.options.dialectFactory({
externalDialectClass: this.options.externalDialectFactory && this.options.externalDialectFactory(context),
schemaVersion: currentSchemaVersion,
preAggregationsSchema: this.preAggregationsSchema(context),
context,
allowJsDuplicatePropsInSchema: this.options.allowJsDuplicatePropsInSchema
}
);
this.compilerCache.set(appId, compilerApi);
}
compilerApi.schemaVersion = currentSchemaVersion;
return compilerApi;
}
说明
以上是结合源码对于cube.js 上下文一个简单说明,可以加深了解
参考资料
https://cube.dev/docs/cube#context-variables-compile-context