@grest-ts/locator

中文文档
0.0.101发布于 2026/11/02MITTypeScriptES Module零依赖近 30 天下载 6861

以树为主的遗产的分级代理背景

中文使用文档
文档目录10 节
  1. 你什么时候需要它?
  2. 基本用途
  3. 定义服务密钥
  4. 案例研究:服务业的依赖性注射
  5. 登记和获取服务
  6. 使用 GGLocator 静态助手
  7. 调试
  8. 范围
  9. GGLocator关键方法
  10. Async 上下文帮助工具

部分 灰尘 框架. 文档 | 所有软件包

定位包 (@ 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(() => { ...
})

版本与发布记录

@grest-ts/locator 共发布 84 个版本,首次发布于 2026/02/24;过去 12 个月发布了 84 个版本。

版本发布日期距今
0.0.101latest2026/11/0214 天前
0.0.1002026/10/3017 天前
0.0.992026/10/3018 天前
0.0.982026/10/2820 天前
0.0.972026/10/2720 天前
0.0.962026/10/2721 天前

关于 @grest-ts/locator 的常见问题

@grest-ts/locator 是什么?

以树为主的遗产的分级代理背景

如何安装 @grest-ts/locator?

在项目目录运行 npm install @grest-ts/locator,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@grest-ts/common(0.0.101)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@grest-ts/locator 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@grest-ts/locator 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@grest-ts/locator 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@grest-ts/locator 可以商用吗?

@grest-ts/locator 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@grest-ts/locator 的下载量有多少?

根据 npm 官方下载统计,@grest-ts/locator 在 2026/10/17 – 2026/11/15 这 30 天内被下载 6,861 次,日均约 229 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@grest-ts/locator 还在维护吗?

最新版本 0.0.101 发布于 2026/11/02(14 天前);至今共发布 84 个版本,其中过去 12 个月发布了 84 个;首次发布于 2026/02/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。