npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@accounts/graphql-api

v0.33.2

Published

Server side GraphQL transport for accounts

Downloads

1,828

Readme

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