# @grantjs/server 中文文档

规范地址：https://npmcn.com/package/%40grantjs/server/

版本：1\.29\.0
npm 元数据更新时间：2026-11-10T14:39:25.382Z
中文译文更新时间：2026-11-17T05:28:27.661Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40grantjs/server
原文对照：https://npmcn.com/package/%40grantjs/server/?lang=original
项目主页：https://github.com/grant-js/grant#readme
源码仓库：https://github.com/grant-js/grant

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

- 包体积（解压后）：188 kB，65 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：next \>=13\.0\.0 \<17\.0\.0，express ^4 \|\| ^5，fastify ^4 \|\| ^5，@nestjs/core \>=10\.0\.0，@nestjs/common \>=10\.0\.0
- 首次发布：2026-03-11T21:07:17.984Z
- 最新版本发布：2026-11-10T14:39:24.782Z
- 近 30 天下载量：5997（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：70（近 12 个月 70 个）

## 中文简介

用于Grant授权的服务器 SDK - 用于快递、快递、雀巢JS和Next.js的中端软件和守卫

## 安装

```sh
npm install @grantjs/server
```

也可以使用：`pnpm add @grantjs/server`、`yarn add @grantjs/server`、`bun add @grantjs/server`

## README

# @ granjs/ 服务器

格兰特授权平台的服务器 SDK. 提供中间软件和警卫 **快递**, (中文(简体) ), **快捷化**, (中文(简体) ), **网点JS**,以及 **下一个.js** 应用.

**联合国** [服务器 SDK](https://github.com/grant-js/grant/blob/main/docs/integration/server-sdk.md) 在官方的文档.

## 特征

-   **基于 REST 的 API** - 本地用途 `fetch`,不需要图形QL客户端
-   **框架整合** - 捷运(`grant()`),快捷化(`grant()`页:1`@Grant` + 键 `GrantGuard`),下册.js (`withGrant()`(中文(简体) )
-   **调试** - 支持授权页眉和饼干
-   **资源解决器** - 条件评估的可选资源分辨率
-   **基于JWT的范围** - 范围取自象征性要求(API-key / 客户端- 秘密流); 不使用请求的会话类范围
-   **类型脚本** - 全面类型安全,类型来自 `@grantjs/schema`
-   **常规** - 使用任何许可模式(使用简单的字符串进行资源/行动)

## 安装

```bash
npm install @grantjs/server
# or
pnpm add @grantjs/server
# or
yarn add @grantjs/server
```

## 实例

每个框架的最小可运行应用 **`examples/`** 并共享相同的 CRUD 表面(文件:Get, POST, PUT, PATCH, DELETE). 从回波根:

```bash
pnpm install
pnpm --filter @grantjs/server build
cd packages/@grantjs/server/examples/express   # or fastify, nextjs, nestjs
cp .env.example .env   # set GRANT_API_URL and optionally GRANT_TOKEN
pnpm start
```

| 示例 | 框架 | 使用量 |
| --- | --- | --- |
| `express` | 快递 | `grant(client, { resource, action })` 中间软件 |
| `fastify` | 快捷化 | `grant(client, { resource, action })` 前汉德勒 |
| `nextjs` | 下一个.js | `withGrant(client, { resource, action }, handler)` aPI线路 |
| `nestjs` | 网点JS | `@Grant(resource, action)` + 键 `GrantGuard`, (中文(简体) ), `GrantModule` |

见 **[实例/README.md](https://npmcn.com/package/%40grantjs/server/examples/README.md)** 为先决条件,路径,和卷曲命令.

## 快速启动

### 1\. 创建客户

```typescript
import { GrantClient } from '@grantjs/server';

// Basic configuration (uses Authorization header or cookies)
const grantClient = new GrantClient({
  apiUrl: 'https://api.grant.com',
});

// With cookie-based auth
const grantClient = new GrantClient({
  apiUrl: 'https://api.grant.com',
  cookieName: 'grant-access-token', // Default: 'grant-access-token'
});

// With custom token extraction
const grantClient = new GrantClient({
  apiUrl: 'https://api.grant.com',
  getToken: (request) => {
    // Custom logic to extract token from request
    const req = request as { headers?: { 'x-api-key'?: string } };
    return req.headers?.['x-api-key'] || null;
  },
});
```

### 2\. 中快件

```typescript
import express from 'express';
import { grant } from '@grantjs/server/express';

const app = express();
const grantClient = new GrantClient({ apiUrl: 'https://api.grant.com' });

// Basic usage
app.get(
  '/organizations',
  grant(grantClient, {
    resource: 'Organization',
    action: 'Query',
  }),
  async (req, res) => {
    // User is authorized, proceed with handler
    res.json({ organizations: [] });
  }
);

// With resource resolver for condition evaluation
app.patch(
  '/projects/:id',
  grant(grantClient, {
    resource: 'Project',
    action: 'Update',
    resourceResolver: async ({ resourceSlug, request }) => {
      // Resolve the project resource for condition evaluation
      const projectId = (request as any).params.id;
      const project = await getProjectById(projectId);
      return project ? { id: project.id, ownerId: project.ownerId } : null;
    },
  }),
  async (req, res) => {
    // User is authorized, proceed with handler
    res.json({ success: true });
  }
);
```

### 3\. 简化插件

```typescript
import Fastify from 'fastify';
import { grantPlugin, grant } from '@grantjs/server/fastify';
import { GrantClient } from '@grantjs/server';

const fastify = Fastify();

// Register the plugin (decorates fastify.grant)
await fastify.register(grantPlugin, {
  apiUrl: 'https://api.grant.com',
  cookieName: 'grant-access-token',
});

// Use preHandler hook
fastify.get(
  '/organizations',
  {
    preHandler: grant(fastify.grant, {
      resource: 'Organization',
      action: 'Query',
    }),
  },
  async (request, reply) => {
    return { organizations: [] };
  }
);

// With resource resolver
fastify.patch(
  '/projects/:id',
  {
    preHandler: grant(fastify.grant, {
      resource: 'Project',
      action: 'Update',
      resourceResolver: async ({ resourceSlug, request }) => {
        const projectId = (request.params as { id: string }).id;
        const project = await getProjectById(projectId);
        return project ? { id: project.id, ownerId: project.ownerId } : null;
      },
    }),
  },
  async (request, reply) => {
    return { success: true };
  }
);
```

### 4\. Next.js (App路由器)

```typescript
// app/api/documents/route.ts
import { NextResponse } from 'next/server';
import { withGrant } from '@grantjs/server/next';
import { GrantClient } from '@grantjs/server';

const grantClient = new GrantClient({ apiUrl: process.env.GRANT_API_URL! });

export const GET = withGrant(grantClient, { resource: 'Document', action: 'Query' }, async () =>
  NextResponse.json({ data: [] })
);

export const POST = withGrant(
  grantClient,
  { resource: 'Document', action: 'Create' },
  async (request) => {
    const body = await request.json();
    return NextResponse.json({ data: { title: body?.title ?? 'Untitled' } }, { status: 201 });
  }
);
```

### 5\. 雀巢协会

```typescript
// app.module.ts
import { GrantModule } from '@grantjs/server/nest';

@Module({
  imports: [
    GrantModule.forRoot({
      apiUrl: process.env.GRANT_API_URL!,
      getToken: (req: any) => req.headers?.authorization?.replace?.('Bearer ', '') ?? null,
    }),
  ],
})
export class AppModule {}

// documents.controller.ts
import { Grant, GrantGuard } from '@grantjs/server/nest';

@Controller('documents')
export class DocumentsController {
  @Get()
  @Grant('Document', 'Query')
  @UseGuards(GrantGuard)
  list() {
    return { data: [] };
  }

  @Post()
  @Grant('Document', 'Create')
  @UseGuards(GrantGuard)
  create(@Body() body: { title?: string }) {
    return { data: { title: body?.title ?? 'Untitled' } };
  }
}
```

登记册 `GrantGuard` 作为您的特性模块中的提供者( 例如) . `providers: [GrantGuard]`)所以巢会注射 `GrantClient`。见 `examples/nestjs` 一个完整的应用程序.

## API 参考

### 赠与客户端

```typescript
const grantClient = new GrantClient(config: GrantServerConfig);
```

#### 配置

```typescript
interface GrantServerConfig {
  // Required
  apiUrl: string;

  // Optional
  cookieName?: string; // Default: 'grant-access-token'
  getToken?: (request: unknown) => string | null | Promise<string | null>;
  fetch?: typeof fetch;
  credentials?: RequestCredentials;
}
```

#### 方法

```typescript
// Permission checks
grantClient.isGranted(resource, action, options?, request?): Promise<boolean>
grantClient.isAuthorized(resource, action, options?, request?): Promise<AuthorizationResult>

// Token extraction
grantClient.getTokenFromRequest(request): Promise<string | null>
```

### 表达式中件

#### `grant(client, options)`

创建 Express 中间软件, 在进行前检查授权 .

**选项 :**

```typescript
interface GrantOptions {
  resource: string; // Resource slug (e.g., "Organization", "Project", "Document")
  action: string; // Action name (e.g., "Query", "Create", "Update", "Delete")
  resourceResolver?: ResourceResolver; // Resource resolution for conditions
}
```

**行为:**

-   回返 `401 Unauthorized` 如果找不到任何符号
-   回返 `404 Not Found` 如果资源解析器返回为无效
-   回返 `403 Forbidden` 如果用户没有权限
-   电话 `next()` 如经核准
-   附 录 `authorization` 结果是 `req.authorization` 用于下游用途
-   授权范围取自JWT(如API-key / 客户端-保密令牌);不取自请求

### 快捷插件

#### `grantPlugin(fastify, options)`

注册一个用于装饰实例的快取插件 `fastify.grant` (GrantClient) (英语).

**选项 :**

与 `GrantServerConfig` - 看见没 [授予客户端配置](https://npmcn.com/package/%40grantjs/server/#readme-grantclient) 见上文.

**用法 :**

```typescript
await fastify.register(grantPlugin, {
  apiUrl: 'https://api.grant.com',
  cookieName: 'grant-access-token',
});

// Now fastify.grant is available
const canEdit = await fastify.grant.isGranted('Document', 'Update', undefined, request);
```

#### `grant(client, options)`

创建快取 `preHandler` 检查授权后再开始.

**选项 :**

与快车相同 `GrantOptions` - 见上文.

**行为:**

-   回返 `401 Unauthorized` 如果找不到任何符号
-   回返 `404 Not Found` 如果资源解析器返回为无效
-   回返 `403 Forbidden` 如果用户没有权限
-   附 录 `authorization` 结果是 `request.authorization` 用于下游用途
-   授权范围取自联合WT;不取自请求

### Next.js (App路由器) (英语)

#### `withGrant(client, options, handler)`

以 Grant 的授权包入 App 路由器路由处理器 。 用于 `GET`, (中文(简体) ), `POST`, (中文(简体) ), `PUT`, (中文(简体) ), `PATCH`, (中文(简体) ), `DELETE` 内 `app/api/.../route.ts`。 。 。 .

**选项 :** 与快车相同 `GrantOptions` (资源,动作,可选资源解析器).

**行为:** 回返 `401` 编号 : `404` 编号 : `403` 失败时的响应; 用 `(request, { authorization })` 在成功方面。 与Next.js 13–16相兼容.

### 网点JS

#### `GrantModule.forRoot(config)`

提供全球模块 `GrantClient` 用于注射。 导入 `AppModule`。 。 。 .

#### `@Grant(resource, action)` 编号 : `Grant(resource, action)`

设置资源/行动元数据 `GrantGuard`与 `@UseGuards(GrantGuard)` 关于控制器方法.

#### `GrantGuard`

读取选项的守护者 `@Grant()` 元数据(或带有可选的清晰构建器选项) `resourceResolver`) (中文(简体) ). 注册为提供者(例如:. `providers: [GrantGuard]`)所以巢会注射 `GrantClient` 财务报告和审定财务报表 `Reflector`出口 `GRANT_CLIENT` 财务报告和审定财务报表 `GRANT_OPTIONS_KEY` 用于高级用途.

## Token 提取器

客户端支持多个符取出方法(按优先排序):

1.  **自定义 `getToken` 函数** (如果有的话)
2.  **授权页眉**数字 : `Authorization: Bearer <token>`
3.  **饼干**: Cookie 名称由 `cookieName` 配置( 默认 ): `grant-access-token`(中文(简体) )

## 资源解析器

资源解析器是解决用于条件评价的资源数据的可选功能. 范围不从中间器件传递(取自API一侧的JWT).

```typescript
const resourceResolver: ResourceResolver = async ({ resourceSlug, request }) => {
  // Fetch resource from database
  const resource = await getResource(resourceSlug, request);

  // Return resource data for condition evaluation
  // e.g., { id: '...', ownerId: '...', status: 'active' }
  return resource ? { id: resource.id, ownerId: resource.ownerId } : null;
};
```

如果解析器返回 `null`,中间软件返回 `404 Not Found`。 。 。 .

## 开发/ 调试

设定 **`DEBUG_GRANT=1`** 在环境(例如: `.env`)启用所有集成(Express, Fastify, Next, Nest)的请求/结果日志. 日志包括资源、行动和授权/拒绝说明理由.

## 处理错误

用于优等错误处理的软件包导出错误分类 :

```typescript
import {
  AuthenticationError, // 401
  AuthorizationError, // 403
  BadRequestError, // 400
  NotFoundError, // 404
} from '@grantjs/server';

try {
  await grantClient.isAuthorized('resource', 'action', undefined, request);
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Handle 401
  } else if (error instanceof AuthorizationError) {
    // Handle 403
  }
}
```

## 类型脚本

完整类型的定义包括:

```typescript
import type {
  GrantServerConfig,
  AuthorizationResult,
  PermissionCheckOptions,
  Scope,
  ResourceResolver,
} from '@grantjs/server';

import { Tenant } from '@grantjs/schema';
```

## 与 @ granjs/ 客户比较

服务器软件包( E)`@grantjs/server`)设计为: **服务器侧** Node.js应用程序,而客户端软件包(`@grantjs/client`用于 **浏览器** 应用.

**密钥差异 :**

| 特性 | @ granjs/ 服务器 | @ granjs/ 客户端 |
| --- | --- | --- |
| **目标** | 节点.js 服务器 | 浏览器应用程序 |
| **缓存** | 否(由API处理) | 是(5min TTL) |
| **调试源** | 请求对象 | 回调函数 |
| **框架支助** | 捷运,快活,雀巢JS,Next.js | 反应, Vue, Svelte, 角 |
| **API 密码** | `grant()` (快递/快递), `withGrant()` (下个), `@Grant` (节日) | `useGrant()` 钩子 |
| **处理错误** | HTTP 状态代码 | 布尔返回 |
| **资源/行动** | 平面字符串( 基因) | 平面字符串( 基因) |

**何时使用 :**

-   **@ granjs/ 服务器**: 保护 API 路由, GraphQL 解析器, 服务器侧中件
-   **@ granjs/ 客户端**: 有条件的 UI 渲染, 客户端许可检查

## 许可证

麻省理工学院

## 常见问题

### @grantjs/server 是什么？

用于Grant授权的服务器 SDK - 用于快递、快递、雀巢JS和Next\.js的中端软件和守卫

### 如何安装 @grantjs/server？

在项目目录运行 npm install @grantjs/server，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：next（\>=13\.0\.0 \<17\.0\.0）、express（^4 \|\| ^5）、fastify（^4 \|\| ^5）、@nestjs/core（\>=10\.0\.0）、@nestjs/common（\>=10\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @grantjs/server 支持 TypeScript 吗？

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

### @grantjs/server 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @grantjs/server 可以商用吗？

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

### @grantjs/server 的下载量有多少？

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

### @grantjs/server 还在维护吗？

最新版本 1\.29\.0 发布于 2026/11/10（6 天前）；至今共发布 70 个版本，其中过去 12 个月发布了 70 个；首次发布于 2026/03/12。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

