@grest-ts/locator

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

Hierarchical async context with tree-based inheritance

原始使用文档
文档目录10 节
  1. When do you need it?
  2. Basic Usage
  3. Defining a Service Key
  4. Case study: Dependency injection (DI) in Services
  5. Registering and Accessing Services
  6. Using GGLocator Static Helpers
  7. Debugging
  8. Scope Branching
  9. GGLocatorKey Methods
  10. Async Context Helpers

Part of the grest-ts framework. Documentation | All packages

Locator Package (@grest-ts/locator)

Service locator pattern implementation using AsyncLocalStorage for managing dependency injection in async contexts. Provides type-safe access to services throughout the request lifecycle without explicit passing.

When do you need it?

  • Framework level: The framework uses GGLocator internally to provide access to services like logging, config, databases, etc.
  • Your services: You can use it to avoid passing service dependencies through deep call stacks. Register once, access anywhere.

Note: GGLocator is for services (long-lived dependencies). For request-scoped data (requestId, auth, etc.), use GGContext instead.

Basic Usage

Defining a Service Key

import {GGLocatorKey} from "@grest-ts/locator"

interface UserService {
    getUser(id: string): Promise<User>
}

const UserServiceKey = new GGLocatorKey<UserService>("UserService")

Case study: Dependency injection (DI) in Services

Explicit, manually passing dependencies. This is what you probably would do for smaller services

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)
    }
}

Using dependency injection via GGLocator keys. Use this when things start getting bigger and you really see value in this.

Pros: Less setup

Cons: Less visibility for dependencies.

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)
    }
}

What NOT to do:

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)
    }
}

But when is direct access fine?

You can always define that some "service" is generic and accessible everywhere. This is for you to decide where you draw the line. Passing Logging, metrics, tracing etc around everywhere can become very tedious, so it is easier to just use inline.

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.
    }
}

Registering and Accessing Services

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")
    }

})

Using GGLocator Static Helpers

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()

Debugging

To see what services are registered in the current scope:

const debugData = GGLocator.getScope().getScopeDebugFull();
console.log(debugData.toString()) // Nicer for console log for a quick peek.
console.log(debugData.toJSON()) // JSON format.

This prints the full scope tree with all registered services and their registration stacks - useful for understanding what's available in your current context.

Scope Branching

Create child scopes that inherit parent services:

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
})

GGLocatorKey Methods

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 Context Helpers

Wrap callbacks to preserve scope across async boundaries:

// 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 是什么?

Hierarchical async context with tree-based inheritance

如何安装 @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 和提交记录判断。