javascript - 通用服务,了解我是在 GRAPHQL 上下文还是 HTTP 上下文中?
问题描述
有什么我可以注入来了解我所处的上下文,即我的服务是从 graphql 请求或 http 请求中调用的。
我有一个请求范围服务,需要返回一个标头。标头存储在REQUEST
对象上,如果它是 HTTP 上下文,或者它在 graphql 上下文中可用(如我之前设置的那样),则可以自动注入该对象 - 因此
return this.request.headers["test"]
或者
return this.context.request.headers["test"]
但我需要了解我所处的上下文以返回正确的对象
有任何想法吗?
提前致谢
解决方案
您可以创建一个辅助函数来检索标头:
getHeader(key: string) {
if (this.request && this.request.headers && this.request.headers[key]) {
return this.request.headers[key];
} else if (this.context.request && this.context.request.headers && this.context.request.headers[key]) {
return this.context.request.headers[key];
} else {
throw new BadRequestException(`Required header ${key} is missing`);
}
}
推荐阅读
- c# - 查找带参数的方法引用
- c# - 有条件地复制数据表行
- html - 使用通用 ngModel 以两种不同的形式共享数据 angular 5
- android - CALL_STATE_IDLE 在第一次拨出电话时被调用?
- json - REST API - JSON 格式一致性
- office-js - 在线工作时无法识别插入到 Desktop PowerPoint 中的内容加载项,反之亦然
- c# - Linq用字符串替换空白
- mysql - 如何从表 WHERE col1+""+col2 LIKE"John D%" 中创建一个 SELECT col1,col2?
- python - 我如何最好地验证熊猫数据框中的电子邮件
- javafx - javafx imageview heightProperty绑定不起作用