# @grest-ts/locator 中文文档

规范地址：https://npmcn.com/package/%40grest-ts/locator/

版本：0\.0\.101
npm 元数据更新时间：2026-11-02T15:34:30.981Z
中文译文更新时间：2026-11-17T04:04:28.482Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40grest-ts/locator
原文对照：https://npmcn.com/package/%40grest-ts/locator/?lang=original
项目主页：https://grest-ts.com/packages/locator
源码仓库：https://github.com/grest-ts/grest-ts

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：65.6 kB，50 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=24
- 运行依赖：0 个
- peer 依赖：@grest-ts/common 0\.0\.101
- 首次发布：2026-02-24T10:54:21.869Z
- 最新版本发布：2026-11-02T15:34:30.788Z
- 近 30 天下载量：6861（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：84（近 12 个月 84 个）

## 中文简介

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

## 安装

```sh
npm install @grest-ts/locator
```

也可以使用：`pnpm add @grest-ts/locator`、`yarn add @grest-ts/locator`、`bun add @grest-ts/locator`

## README

> 部分 [灰尘](https://github.com/grest-ts/grest-ts) 框架. [文档](https://github.com/grest-ts/grest-ts#readme) | [所有软件包](https://github.com/grest-ts/grest-ts#package-reference)

# 定位包 (@ grest- ts/ 定位器)

使用 Async LocalStorage 执行服务定位器模式,在Async 语境下管理依赖性注射. 在整个请求使用周期内提供类型安全服务,不 明确通过.

## 你什么时候需要它?

-   **框架一级**:框架内部使用GGLocator,提供登录,配置,数据库等服务.
-   **您的服务**: 您可以用它来避免通过深层调用堆栈传递服务依赖性. 登记一次,进入任何地方.

注:GGLocator是用于 **服务** (长生相依. 用于请求范围的数据(requestId, auth等),使用 `GGContext` 换句话说.

## 基本用途

### 定义服务密钥

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

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

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

### 案例研究:服务业的依赖性注射

明确,人工传递的依赖关系. 这是你可能做的 对于较小的服务

```typescript
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: 少设置

康斯:依赖性的能见度较低.

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

不做什麽:

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

但是,什么时候直接进入是罚款?

你总是可以定义一些"服务"是通用的,并且可以到处访问. 这是由你决定你画线的位置. 到处传来伐木,度量衡,追踪等都可能变得很乏味,所以比较容易使用内线.

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

### 登记和获取服务

```typescript
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 静态助手

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

## 调试

要了解在当前范围内登记哪些服务:

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

此打印了所有已注册服务的全范围树及其注册堆 - 用于了解您当前上下文中可用的内容 .

## 范围

创建继承父服务的儿童范围:

```typescript
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关键方法

```typescript
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 上下文帮助工具

环绕调用以保留跨同步边界的范围 :

```typescript
// 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 是什么？

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

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

