@accounts/graphql-api

中文文档
0.33.2发布于 2022/01/17MITTypeScriptCommonJS近 30 天下载 9265

Server side GraphQL transport for accounts

原始使用文档
文档目录7 节
  1. How to use this package?
  2. Authenticating Resolvers
  3. Customization
  4. Extending User
  5. Extending User during password creation
  6. Example: Authenticate with a Service
  7. Verify Authentication

@accounts/graphql-api

Schema, Resolvers and Utils for GraphQL server with JSAccounts

npm MIT License

This package does not requires any network interface / express in order to combine with your GraphQL - it's just a collection of GraphQL schema, resolvers and utils!

How to use this package?

This package exports GraphQL schema and GraphQL resolvers, which you can extend with your existing GraphQL schema server.

Start by installing it from NPM / Yarn:

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

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

This package does not create a transport or anything else, only schema and string and resolvers as object.

Start by configuring your AccountsServer as you wish. For example, using MongoDB:

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

Next, import AccountsModule from this package, and run it with your AccountsServer:

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

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

Now, add accountsGraphQL.typeDefs to your schema definition (just before using it with makeExecutableSchema), and merge your resolvers object with accountsGraphQL.resolvers by using @graphql-tools/epoxy, for example:

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]),
});

The last step is to extend your graphqlExpress with a context middleware, that extracts the authentication token from the HTTP request, so AccountsServer will automatically validate it:

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

Authenticating Resolvers

You can authenticate your own resolvers with JSAccounts authentication flow, by using authenticated method from this package.

This method composer also extends context with the current authenticated user!

This is an example for a protected mutation:

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!
    }),
  },
};

Customization

This package allow you to customize the GraphQL schema and it's resolvers.

For example, some application main query called MyQuery or RootQuery instead of query, so you can customize the name, without modifying you application's schema.

These are the available customizations:

  • rootQueryName (string) - The name of the root query, default: Query.
  • rootMutationName (string) - The name of the root mutation, default: Mutation.
  • extend (boolean) - whether to add extend before the root type declaration, default: true.
  • withSchemaDefinition (boolean): whether to add schema { ... } declaration to the generation schema, default: false.

Pass a second object to createAccountsGraphQL, for example:

Another possible customization is to modify the name of the authentication header, use it with accountsContext (the default is Authorization):

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

Extending User

To extend User object with custom fields and logic, add your own GraphQL type definition of User with the prefix of extend, and add your fields:

extend type User {
  firstName: String
  lastName: String
}

And also implement a regular resolver, for the fields you added:

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

Extending User during password creation

To extend the user object during the user creation you need to extend the CreateUserInput type and add your fields:

extend input CreateUserInput {
  profile: CreateUserProfileInput!
}

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

The user will be saved in the db with the profile key set.

Example: Authenticate with a Service

mutation Authenticate {
  authenticate(serviceName: "password", params: { password: "<pw>", user: { email: "<email>" } })
}
  1. serviceName - corresponds to the package you are using to authenticate (e.g. oauth, password, twitter, instagram, two factor, token, etc).
  2. params - These will be different depending on the service you are using.
  • Twitter/Instagram
mutation Authenticate {
  authenticate(
    serviceName: "twitter"
    params: { access_token: "<access-token>", access_token_secret: "<access-token-secret>" }
  )
}
  • OAuth
mutation Authenticate {
  authenticate(serviceName: "oauth", params: { provider: "<your-provider>" })
}
  • Password: Below the user contains email but can contain one or more of id, email or username too.
mutation Authenticate {
  authenticate(serviceName: "password", params: { password: "<pw>", user: { email: "<email>" } })
}
  • Two Factor
mutation Authenticate {
  authenticate(serviceName: "two-factor", params: { code: "<two-factor-code>" })
}
  • Token
mutation Authenticate {
  authenticate(serviceName: "token", params: { token: "<token>" })
}

Verify Authentication

The way to check if a user has been successfully authenticated is identical, with the exception that verifyAuthentication returns a boolean instead of a LoginResult:

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

This will return a result similar to this, if your user has been successfully authenticated:

{
  "data": {
    "verifyAuthentication": true
  }
}

版本与发布记录

@accounts/graphql-api 共发布 102 个版本,首次发布于 2017/02/24;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.33.2latest2022/01/174 年前
0.33.12021/10/135 年前
0.33.02021/07/255 年前
0.32.02021/04/225 年前
0.31.12021/02/015 年前
0.31.02021/02/015 年前

其他发布通道:canary → 0.24.1-alpha.12,next → 0.30.0-alpha.1。

关于 @accounts/graphql-api 的常见问题

@accounts/graphql-api 是什么?

Server side GraphQL transport for accounts

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