# @accounts/graphql-api 中文文档

规范地址：https://npmcn.com/package/%40accounts/graphql-api/

版本：0\.33\.2
npm 元数据更新时间：2022-06-12T14:15:46.885Z
中文译文更新时间：2026-11-05T23:40:14.107Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：126 kB，111 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- peer 依赖：@accounts/magic-link ^0\.1\.0，@accounts/password ^0\.32\.0，@accounts/server ^0\.32\.0 \|\| ^0\.33\.0，@accounts/types ^0\.32\.0 \|\| ^0\.33\.0，@graphql-modules/core 0\.7\.17，graphql ^14\.6\.0 \|\| ^15\.0\.0，graphql-tag ^2\.10\.0
- 首次发布：2017-02-23T16:27:04.800Z
- 最新版本发布：2022-01-17T10:11:42.589Z
- 近 30 天下载量：9265（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：102（近 12 个月 0 个）

## 中文简介

服务器侧图QL 传输账户

## 安装

```sh
npm install @accounts/graphql-api
```

也可以使用：`pnpm add @accounts/graphql-api`、`yarn add @accounts/graphql-api`、`bun add @accounts/graphql-api`

## README

# @ accounts/graphql-api 账户

_带有 JS 账户的 GraphQL 服务器的 Schema、 解析器和 Utils_

[![npm](https://img.shields.io/npm/v/@accounts/graphql-api.svg?maxAge=2592000)](https://www.npmjs.com/package/@accounts/graphql-api) ![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)

> 此软件包不需要任何网络接口 / express 来与您的 GraphQL 组合 - 这只是 GraphQL 的图集, 解析器和 utils !

## 如何使用这个包裹?

此软件包将导出 GraphQL 策略和 GraphQL 解析器, 您可以用您现有的 GraphQL 策略服务器扩展 .

从国家防范机制/亚恩安装开始:

```bash
// Npm
npm install --save @accounts/server @accounts/graphql-api @graphql-modules/core

// Yarn
yarn add @accounts/server @accounts/graphql-api @graphql-modules/core
```

> 此软件包不创建传送器或其他任何设备,仅将图案和字符串及解析器作为对象.

从配置开始 `AccountsServer` 随你便 例如,使用MongoDB:

```js
import mongoose from 'mongoose'
import AccountsServer from '@accounts/server'
import AccountsPassword from '@accounts/password'
import MongoDBInterface from '@accounts/mongo'

const db = mongoose.connection

const password = new AccountsPassword()

const accountsServer = new AccountsServer({
  {
    db: new MongoDBInterface(db),
    tokenSecret: 'SECRET',
  },
  {
    password,
  }
});
```

下一个,导入 `AccountsModule` 从这个包,运行它与您的 `AccountsServer`数字 :

```js
import { AccountsModule } from '@accounts/graphql-api';

const accountsGraphQL = AccountsModule.forRoot({
  accountsServer,
});
```

现在,添加 `accountsGraphQL.typeDefs` 到您的计划定义( 在使用它之前) `makeExecutableSchema`,然后将您的解析器对象与 `accountsGraphQL.resolvers` 通过使用 `@graphql-tools/epoxy`,例如:

```js
import { makeExecutableSchema } from '@graphql-tools/schema';
import { mergeGraphQLSchemas, mergeResolvers } from '@graphql-tools/epoxy';

const typeDefs = [
  `
  type Query {
    myQuery: String
  }

  type Mutation {
    myMutation: String
  }

  schema {
      query: Query,
      mutation: Mutation
  }
  `,
  accountsGraphQL.typeDefs,
];

let myResolvers = {
  Query: {
    myQuery: () => 'Hello',
  },
  Mutation: {
    myMutation: () => 'Hello',
  },
};

const schema = makeExecutableSchema({
  resolvers: mergeResolvers([accountsGraphQL.resolvers, myResolvers]),
  typeDefs: mergeGraphQLSchemas([typeDefs]),
});
```

最后一步是扩展你 `graphqlExpress` 带有上下文中间软件,从 HTTP 请求中提取认证令牌,因此 AccountsServer 会自动验证它:

```js
app.use(
  GRAPHQL_ROUTE,
  bodyParser.json(),
  graphqlExpress((request) => {
    return {
      context: {
        ...accountsGraphQL(request),
        // your context
      },
      schema,
    };
  })
);
```

## 认证解析器

你可以证明自己的决心 `JSAccounts` 通过使用 `authenticated` 方法.

这种方法作曲家也延伸 `context` 使用当前认证的用户 !

这是受保护突变的例子:

```js
import AccountsServer from '@accounts/server';
import { authenticated } from '@accounts/graphql-api';

export const resolver = {
  Mutation: {
    updateUserProfile: authenticated((rootValue, args, context) => {
      // Write your resolver here
      // context.user - the current authenticated user!
    }),
  },
};
```

## 自定义

此软件包允许您自定义 GraphQL 方案, 它是解析器 .

例如,一些应用程序主查询被调用 `MyQuery` 或者说 `RootQuery` 而不是查询,所以您可以自定义名称,而不修改应用程序的设置.

这些是现有的定制:

-   `rootQueryName` (字符串) - 根查询的名称, 默认 : `Query`。 。 。 .
-   `rootMutationName` (字符串) - 根突变的名称,默认: `Mutation`。 。 。 .
-   `extend` (boolean) - 是否添加 `extend` 在根类型声明前,默认: `true`。 。 。 .
-   `withSchemaDefinition` (布尔语):是否添加 `schema { ... }` 向生成计划声明, 默认: `false`。 。 。 .

通过第二个对象 `createAccountsGraphQL`,例如:

另一种可能的定制是修改认证头的名称,使用它 `accountsContext` (默认为 `Authorization`:

```js
const myCustomGraphQLAccounts = AccountsModule.forRoot({
  accountsServer,
  rootQueryName: 'RootQuery',
  rootMutationName: 'RootMutation',
  headerName: 'MyCustomHeader',
});
```

## 扩展 `User`

延长 `User` 对象带有自定义字段和逻辑,添加您自己的 GraphQL 类型定义 `User` 带有前缀 `extend`,并添加您的字段:

```graphql
extend type User {
  firstName: String
  lastName: String
}
```

并且为您添加的字段执行固定解析器:

```js
const UserResolver = {
  firstName: () => 'Dotan',
  lastName: () => 'Simha',
};
```

## 扩展 `User` 密码创建期间

要在用户创建期间扩展用户对象,您需要扩展 `CreateUserInput` 键入并添加您的字段 :

```graphql
extend input CreateUserInput {
  profile: CreateUserProfileInput!
}

input CreateUserProfileInput {
  firstName: String!
  lastName: String!
}
```

用户将随配置文件密钥集被保存在 db 中 .

## 示例:使用服务认证

```graphql
mutation Authenticate {
  authenticate(serviceName: "password", params: { password: "<pw>", user: { email: "<email>" } })
}
```

1.  `serviceName` - 与您用来认证的软件包相对应(例如:oauth、密码、twitter、instagram、两个系数、指使等).
2.  `params` - 这些会不同 取决于你使用的服务.

-   推特/Instagram

```graphql
mutation Authenticate {
  authenticate(
    serviceName: "twitter"
    params: { access_token: "<access-token>", access_token_secret: "<access-token-secret>" }
  )
}
```

-   奥奥特

```graphql
mutation Authenticate {
  authenticate(serviceName: "oauth", params: { provider: "<your-provider>" })
}
```

-   密码: 下方 `user` 包含 `email` 但可以包含一个或多个 `id`, (中文(简体) ), `email` 或者说 `username` 我也一样.

```graphql
mutation Authenticate {
  authenticate(serviceName: "password", params: { password: "<pw>", user: { email: "<email>" } })
}
```

-   两个因素

```graphql
mutation Authenticate {
  authenticate(serviceName: "two-factor", params: { code: "<two-factor-code>" })
}
```

-   脚本

```graphql
mutation Authenticate {
  authenticate(serviceName: "token", params: { token: "<token>" })
}
```

### 校验认证

检查用户是否成功认证的方法是相同的,但 `verifyAuthentication` 返回 a `boolean` 而不是一个 `LoginResult`数字 :

```graphql
mutation Verify {
  verifyAuthentication(
    serviceName: "password"
    params: { password: "<pw>", user: { email: "<email>" } }
  )
}
```

如果用户已成功认证, 这将返回类似此结果 :

```json
{
  "data": {
    "verifyAuthentication": true
  }
}
```

## 常见问题

### @accounts/graphql-api 是什么？

服务器侧图QL 传输账户

### 如何安装 @accounts/graphql-api？

在项目目录运行 npm install @accounts/graphql-api，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@accounts/magic-link（^0\.1\.0）、@accounts/password（^0\.32\.0）、@accounts/server（^0\.32\.0 \|\| ^0\.33\.0）、@accounts/types（^0\.32\.0 \|\| ^0\.33\.0）、@graphql-modules/core（0\.7\.17）、graphql（^14\.6\.0 \|\| ^15\.0\.0）、graphql-tag（^2\.10\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @accounts/graphql-api 支持 TypeScript 吗？

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

### @accounts/graphql-api 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @accounts/graphql-api 可以商用吗？

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

### @accounts/graphql-api 的下载量有多少？

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

### @accounts/graphql-api 还在维护吗？

最新版本 0\.33\.2 发布于 2022/01/17（4 年前）；至今共发布 102 个版本，其中过去 12 个月发布了 0 个；首次发布于 2017/02/24。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

