定位包 (@ grest- ts/ 定位器)
使用 Async LocalStorage 执行服务定位器模式,在Async 语境下管理依赖性注射. 在整个请求使用周期内提供类型安全服务,不 明确通过.
你什么时候需要它?
- 框架一级:框架内部使用GGLocator,提供登录,配置,数据库等服务.
- 您的服务: 您可以用它来避免通过深层调用堆栈传递服务依赖性. 登记一次,进入任何地方.
注:GGLocator是用于 服务 (长生相依. 用于请求范围的数据(requestId, auth等),使用 GGContext 换句话说.
基本用途
定义服务密钥
import {GGLocatorKey} from "@grest-ts/locator"
interface UserService {
getUser(id: string): Promise<User>
}
const UserServiceKey = new GGLocatorKey<UserService>("UserService")
案例研究:服务业的依赖性注射
明确,人工传递的依赖关系. 这是你可能做的 对于较小的服务
class OrderService {
private readonly userService: UserService
private readonly paymentService: PaymentService
constructor(userService: UserService, paymentService: PaymentService) {
this.userService = userService
this.paymentService = paymentService
}
async createOrder(userId: string, items: Item[]) {
const user = await this.userService.getUser(userId)
return this.paymentService.charge(user, items)
}
}
通过GGLocator键使用依赖性注射. 用这个当事情开始变大, 你真正看到价值在这里.
Pros: 少设置
康斯:依赖性的能见度较低.
class OrderService {
private readonly userService = UserServiceKey.get()
private readonly paymentService = PaymentServiceKey.get()
async createOrder(userId: string, items: Item[]) {
const user = await this.userService.getUser(userId)
return this.paymentService.charge(user, items)
}
}
不做什麽:
class OrderService {
async createOrder(userId: string, items: Item[]) {
// VERY BAD: Keeps the dependency "hidden" and causes issues for your project in the future.
const user = await UserServiceKey.get().getUser(userId)
return PaymentServiceKey.get().charge(user, items)
}
}
但是,什么时候直接进入是罚款?
你总是可以定义一些"服务"是通用的,并且可以到处访问. 这是由你决定你画线的位置. 到处传来伐木,度量衡,追踪等都可能变得很乏味,所以比较容易使用内线.
class OrderService {
async createOrder(userId: string, items: Item[]) {
// Important - all these next examples are still async context scoped.
GGLog.info(this, "Some log message") // Library itself provides quick access is usually a hint it is meant to be used like this.
MyMetrics.orders.increment("orders.created") // Metrics are usually defined globally and accessible everywhere.
const isEnabled = MyConfig.something.somewhere.get() // Config is usually defined globally and accessible everywhere.
}
}
登记和获取服务
import {GGLocatorScope} from "@grest-ts/locator"
// You usually don't need to create the scope, but for the completeness of this example, we create it here.
new GGLocatorScope("something").run(async () => {
// Set the service
UserServiceKey.set(new UserServiceImpl())
// Set the service
UserServiceKey.overwrite(new UserServiceImpl())
// Access service anywhere in the call stack
const userService = UserServiceKey.get() // Throws if service is not set.
const user = await userService.getUser("123")
// Optionally get the service
const userServiceOpt = UserServiceKey.tryGet()
if (userServiceOpt) {
const user = await userServiceOpt.getUser("123")
}
})
使用 GGLocator 静态助手
import {GGLocator} from "@grest-ts/locator"
// Check if scope exists
if (GGLocator.hasScope()) {
const scope = GGLocator.getScope()
}
// Safe access (returns undefined if no scope)
const scope = GGLocator.tryGetScope()
调试
要了解在当前范围内登记哪些服务:
const debugData = GGLocator.getScope().getScopeDebugFull();
console.log(debugData.toString()) // Nicer for console log for a quick peek.
console.log(debugData.toJSON()) // JSON format.
此打印了所有已注册服务的全范围树及其注册堆 - 用于了解您当前上下文中可用的内容 .
范围
创建继承父服务的儿童范围:
const rootScope = new GGLocatorScope("root")
rootScope.set(ConfigKey, config)
// Child scope inherits parent services
const requestScope = rootScope.branch("request")
requestScope.set(RequestContextKey, requestContext)
requestScope.run(() => {
ConfigKey.get() // Works - inherited from parent
RequestContextKey.get() // Works - set in this scope
})
GGLocator关键方法
const ServiceKey = new GGLocatorKey<MyService>("MyService")
// Get service (throws if not found)
const service = ServiceKey.get()
// Try get service (returns undefined if not found)
const service = ServiceKey.tryGet()
// Check if service exists
if (ServiceKey.has()) { ...
}
// Set service (throws if already set)
ServiceKey.set(new MyService())
// Overwrite service (allows replacing)
ServiceKey.overwrite(new MyService())
Async 上下文帮助工具
环绕调用以保留跨同步边界的范围 :
// Wrap function to run within current scope
const wrappedFn = GGLocator.wrapWithRun(myCallback)
// Schedule with scope preservation
GGLocator.setTimeout(() => {
// Scope is preserved here
ServiceKey.get()
}, 1000)
GGLocator.setInterval(() => { ...
}, 5000)
GGLocator.setImmediate(() => { ...
})