# @koikorn/keystone

> The main @koikorn class & CLI. This is where the magic happens.

Latest version **11.2.0** (published 2020-07-13) · MIT license · 0 weekly downloads

## Install

```sh
npm install @koikorn/keystone
pnpm add @koikorn/keystone
yarn add @koikorn/keystone
bun add @koikorn/keystone
```

Provides the command `keystone`.

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: no vulnerabilities; high maintenance score.

Warnings: low downloads; no types; no esm support.

Negative: abandoned.

## Facts

| | |
|---|---|
| Version | 11.2.0 |
| Published | 2020-07-13 |
| First published | 2020-07-11 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >=10.0.0 |
| Dependencies | 27 |
| Unpacked size | 239.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 9972 |
| Author | The KeystoneJS Development Team |
| Maintainers | lorenhaim |

## Links

- npm: https://www.npmjs.com/package/@koikorn/keystone
- Repository: https://github.com/keystonejs/keystone/tree/master/packages/keystone
- npm.io page: https://npm.io/package/@koikorn/keystone

## Dependencies (27)

- [arg](https://npm.io/package/arg.md) ^4.1.1
- [ora](https://npm.io/package/ora.md) ^3.4.0
- [cors](https://npm.io/package/cors.md) ^2.8.4
- [chalk](https://npm.io/package/chalk.md) ^2.4.2
- [endent](https://npm.io/package/endent.md) ^1.3.0
- [falsey](https://npm.io/package/falsey.md) ^1.0.0
- [globby](https://npm.io/package/globby.md) ^11.0.0
- [ci-info](https://npm.io/package/ci-info.md) ^2.0.0
- [express](https://npm.io/package/express.md) ^4.17.1
- [graphql](https://npm.io/package/graphql.md) ^14.6.0
- [dev-null](https://npm.io/package/dev-null.md) ^0.1.1
- [fs-extra](https://npm.io/package/fs-extra.md) ^7.0.0
- [pluralize](https://npm.io/package/pluralize.md) ^7.0.0
- [graphql-tag](https://npm.io/package/graphql-tag.md) ^2.10.3
- [p-waterfall](https://npm.io/package/p-waterfall.md) ^2.1.0
- [apollo-errors](https://npm.io/package/apollo-errors.md) ^1.9.0
- [micro-memoize](https://npm.io/package/micro-memoize.md) ^4.0.9
- [terminal-link](https://npm.io/package/terminal-link.md) ^1.3.0
- [@koikorn/utils](https://npm.io/package/@koikorn/utils.md) ^5.4.2
- [@koikorn/fields](https://npm.io/package/@koikorn/fields.md) ^13.0.2
- [@koikorn/logger](https://npm.io/package/@koikorn/logger.md) ^5.1.2
- [@koikorn/session](https://npm.io/package/@koikorn/session.md) ^7.0.1
- [graphql-type-json](https://npm.io/package/graphql-type-json.md) ^0.3.1
- [lodash.flattendeep](https://npm.io/package/lodash.flattendeep.md) ^4.4.0
- [express-pino-logger](https://npm.io/package/express-pino-logger.md) ^4.0.0
- [@koikorn/app-version](https://npm.io/package/@koikorn/app-version.md) ^1.0.2
- [@koikorn/access-control](https://npm.io/package/@koikorn/access-control.md) ^6.2.0

## Recent versions

- 11.2.0 (latest) — 2020-07-13
- 1.0.0 — 2020-07-11

## README

<!--[meta]
section: api
title: Keystone class
order: 1
[meta]-->

# Keystone class

## Usage

```javascript
const { Keystone } = require('@koikorn/keystone');

const keystone = new Keystone({
  adapter,
  adapters,
  appVersion,
  cookie,
  cookieSecret,
  defaultAccess,
  defaultAdapter,
  onConnect,
  queryLimits,
  sessionStore,
  schemaNames,
});
```

### `appVersion`

Configure the application version, which can be surfaced via HTTP headers or GraphQL.

The `version` can be any string value you choose to use for your system. If `addVersionToHttpHeaders` is `true` then all requests will have the header `X-Keystone-App-Version` set. The version can also be queried from the GraphQL API as `{ appVersion }`. You can control whether this is exposed in your schema using `access`, which can be either a boolean, or an object with `schemaName` keys and boolean values.

```javascript
const keystone = new Keystone({
  appVersion: {
    version: '1.0.0',
    addVersionToHttpHeaders: true,
    access: true,
  },
});
```

#### Why don't we just use `access` to control the HTTP header?

> We want to attach the HTTP header at the very top of the middleware stack, so if something gets rejected we can at least be sure of the system version that did the rejecting. This happens well before we have worked out which schema the person is trying to access, and therefore our access control isn’t ready to be used. Also, the access control that we set up is all about controlling access to the GraphQL API, and HTTP headers are a Different Thing, so even if it was technically possible to use the same mechanism, it really makes sense to decouple those two things.

### `cookie`

_**Default:**_ see Usage.

A description of the cookie properties is included in the [express-session documentation](https://github.com/expressjs/session#cookie).

#### `secure`

A secure cookie is only sent to the server with an encrypted request over the HTTPS protocol. If `secure` is set to true (as is the default with a **production** build) for a KeystoneJS project running on a non-HTTPS server (such as localhost), you will **not** be able to log in. In that case, be sure you set `secure` to false. This does not affect development builds since this value is already false.

You can read more about secure cookies on the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies).

#### Usage

```javascript
const keystone = new Keystone({
  /* ...config */
  cookie: {
    secure: process.env.NODE_ENV === 'production', // Default to true in production
    maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
    sameSite: false,
  },
});
```

### `cookieSecret`

The secret used to sign session ID cookies. In production mode (`process.env.NODE_ENV === 'production'`) this option is required. In development mode, if undefined, a random `cookieSecret` will be generated each time Keystone starts (this will cause sessions to be reset between restarts).

### `defaultAccess`

_**Default:**_

```js
{
  list: true,
  field: true,
  custom: true
}
```

Default list and field access. See the [Access Control](https://www.keystonejs.com/api/access-control#defaults) page for more details.

### `defaultAdapter`

_**Default:**_ `undefined`

The name of the database adapter to use by default if multiple are provided.

### `onConnect`

_**Default:**_ `undefined`

Callback function that executes once `keystone.connect()` is complete. Takes no arguments.

### `queryLimits`

Configures global query limits.

These should be used together with [list query limits](https://keystonejs.com/api/create-list#query-limits).

```javascript
const keystone = new Keystone({
  queryLimits: {
    maxTotalResults: 1000,
  },
});
```

- `maxTotalResults`: limit of the total results of all relationship subqueries

Note that `maxTotalResults` applies to the total results of all relationship queries separately, even if some are nested inside others.

### `sessionStore`

Sets the Express server's [session middleware](https://github.com/expressjs/session). This should be configured before deploying your app.

This example uses the [`connect-mongo`](https://github.com/jdesboeufs/connect-mongo) middleware, but you can use [any of the stores that work with `express session`](https://github.com/expressjs/session#compatible-session-stores).

```javascript
const expressSession = require('express-session');
const MongoStore = require('connect-mongo')(expressSession);

const keystone = new Keystone({
  sessionStore: new MongoStore({ url: 'mongodb://localhost/my-app' }),
});
```

### `schemaNames`

_**Default:**_ `['public']`

## Methods

| Method                | Description                                                                  |
| --------------------- | ---------------------------------------------------------------------------- |
| `connect`             | Manually connect to Adapters.                                                |
| `createAuthStrategy`  | Creates a new authentication middleware instance.                            |
| `createItems`         | Add items to a `Keystone` list.                                              |
| `createList`          | Add a list to the `Keystone` schema.                                         |
| `disconnect`          | Disconnect from all adapters.                                                |
| `extendGraphQLSchema` | Extend keystones generated schema with custom types, queries, and mutations. |
| `prepare`             | Manually prepare `Keystone` middlewares.                                     |
| `createContext`       | Create a `context` object that can be used with `executeGraphQL()`.          |
| `executeGraphQL`      | Execute a server-side GraphQL operation within the given context.            |

<!--
## Super secret methods

Hello curious user. Here are some undocumented methods you _can_ use.
Please note: We use these internally but provide no support or assurance if used in your projects.

| Method                | Description                                                                  |
| --------------------- | ---------------------------------------------------------------------------- |
| `dumpSchema`          | Dump schema to a string.                                                       |
| `getTypeDefs`         | Remove from user documentation?                                              |
| `getResolvers`        | Remove from user documentation?                                              |
| `registerSchema`      | Remove from user documentation?                                              |
| `createItem`          | Remove from user documentation?                                              |
| `getAdminMeta`        | Remove from user documentation?                                              |
-->

### `connect()`

Manually connect Keystone to the adapters. See [Custom Server](https://keystonejs.com/guides/custom-server).

```javascript allowCopy=false showLanguage=false
keystone.connect();
```

> **Note:** `keystone.connect()` is only required for custom servers. Most example projects use the `keystone start` command to start a server and automatically connect.

### `createAuthStrategy(config)`

Creates a new authentication middleware instance. See:

- [Authentication guide](https://www.keystonejs.com/guides/authentication)
- [Authentication API docs](https://www.keystonejs.com/api/authentication)

```javascript allowCopy=false showLanguage=false
const authStrategy = keystone.createAuthStrategy({...});
```

### `createItems(items)`

Allows bulk creation of items. This method's primary use is intended for migration scripts, or initial seeding of databases.

```javascript
keystone.createItems({
  User: [{ name: 'Ticiana' }, { name: 'Lauren' }],
  Post: [
    {
      title: 'Hello World',
      author: { where: { name: 'Ticiana' } },
    },
  ],
});
```

The `author` field of the `Post` list would have the following configuration:

```javascript
keystone.createList('Post', {
  fields: {
    author: { type: Relationship, ref: 'User' },
  },
});
```

#### Config

| Option      | Type     | Description                                                                     |
| ----------- | -------- | ------------------------------------------------------------------------------- |
| `[listKey]` | `Object` | An object where keys are list keys, and values are an array of items to insert. |

_Note_: The format of the data must match the lists and fields setup with `keystone.createList()`

It is possible to create relationships at insertion using the Keystone query syntax.

E.g. `author: { where: { name: 'Ticiana' } }`

Upon insertion, Keystone will resolve the `{ where: { name: 'Ticiana' } }` query
against the `User` list, ultimately setting the `author` field to the ID of the
_first_ `User` that is found.

Note an error is thrown if no items match the query.

### `createList(listKey, config)`

Registers a new list with Keystone and returns a `Keystone` list object. See:

- [Adding lists tutorial](/docs/tutorials/add-lists.md)
- [Data modelling guide](/docs/guides/schema.md)

```javascript allowCopy=false showLanguage=false
keystone.createList('Posts', {...});
```

#### Config

| Option    | Type     | Default | Description                                                                                 |
| --------- | -------- | ------- | ------------------------------------------------------------------------------------------- |
| `listKey` | `String` | `null`  | The name of the list. This should be singular, E.g. 'User' not 'Users'.                     |
| `config`  | `Object` | `{}`    | The list config. See the [create list API docs](/docs/api/create-list.md) for more details. |

### `disconnect()`

Disconnect all adapters.

### `extendGraphQLSchema(config)`

Extends keystones generated schema with custom types, queries, and mutations.

```javascript
keystone.extendGraphQLSchema({
  types: [{ type: 'type MyType { original: Int, double: Float }' }],
  queries: [
    {
      schema: 'double(x: Int): MyType',
      resolver: (_, { x }) => ({ original: x, double: 2.0 * x }),
    },
  ],
  mutations: [
    {
      schema: 'triple(x: Int): Int',
      resolver: (_, { x }) => 3 * x,
    },
  ],
});
```

See the [Custom schema guide](/docs/guides/custom-schema.md) for more information on utilizing custom schema.

#### Config

| Option    | Type    | Description                                                                                    |
| --------- | ------- | ---------------------------------------------------------------------------------------------- |
| types     | `array` | A list of objects of the form `{ type, access }` where the type string defines a GraphQL type. |
| queries   | `array` | A list of objects of the form `{ schema, resolver, access }`.                                  |
| mutations | `array` | A list of objects of the form `{ schema, resolver, access }`.                                  |

- The `schema` for both queries and mutations should be a string defining the GraphQL schema element for the query/mutation, e.g.

```javascript
{
  schema: 'getBestPosts(author: ID!): [Post]',
}
```

- The `resolver` for both queries and mutations should be a resolver function with following signature:

```javascript
{
  resolver: (parent, args, context, info, extra) => {},
}
```

For more information about the first four arguments, please see the [Apollo docs](https://www.apollographql.com/docs/apollo-server/data/resolvers/#resolver-arguments). The last argument `extra` is an object that contains the following property:

| Name     | Description                                        |
| -------- | -------------------------------------------------- |
| `access` | Access control information about the current user. |

- The `access` argument for `types`, `queries`, and `mutations` are all either boolean values which are used at schema generation time to include or exclude the item from the schema, or a function which must return boolean.
- See the [Access control API](https://www.keystonejs.com/api/access-control#custom-schema-access-control) docs for more details.

### `prepare(config)`

Manually prepare middlewares. Returns a promise representing the processed middlewares. They are available as an array through the `middlewares` property of the returned object.

#### Usage

```javascript
const { middlewares } = await keystone.prepare({
  apps,
  dev: process.env.NODE_ENV !== 'production',
});
```

#### Config

| Option        | Type      | default                               | Description                                                                                                         |
| ------------- | --------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `apps`        | `Array`   | `[]`                                  | An array of 'Apps' which are express middleware.                                                                    |
| `cors`        | `Object`  | `{ origin: true, credentials: true }` | CORS options passed to the [`cors` npm module](https://www.npmjs.com/package/cors)                                  |
| `dev`         | `Boolean` | `false`                               | Sets the dev flag in Keystone' express middleware.                                                                  |
| `distDir`     | `String`  | `dist`                                | The build directory for keystone.                                                                                   |
| `pinoOptions` | `Object`  | `undefined`                           | Logging options passed to the [`express-pino-logger` npm module](https://www.npmjs.com/package/express-pino-logger) |

### `createContext({ schemaName, authentication, skipAccessControl })`

Create a `context` object that can be used with `executeGraphQL()`.

#### Usage

```javascript
const { gql } = require('apollo-server-express');

// Create a context which can execute GraphQL operations with no access control
const context = keystone.createContext({ skipAccessControl: true })

// Execute a GraphQL operation with no access control
const { data, errors } = keystone.executeGraphQL({ context, query: gql` ... `, variables: { ... }})
```

#### Config

| Option              | Type      | default  | Description                                                                                  |
| ------------------- | --------- | -------- | -------------------------------------------------------------------------------------------- |
| `schemaName`        | `String`  | `public` | The name of the GraphQL schema to execute against.                                           |
| `authentication`    | `Object`  | `{}`     | `{ item: { id }, listAuthKey: "" }`. Specifies the item to be used in access control checks. |
| `skipAccessControl` | `Boolean` | `false`  | Set to `true` to skip all access control checks.                                             |

### `executeGraphQL({ context, query, variables })`

Execute a server-side GraphQL query within the given context.

#### Usage

```javascript
const { gql } = require('apollo-server-express');

// Create a context which can execute GraphQL operations with no access control
const context = keystone.createContext({ skipAccessControl: true })

// Execute a GraphQL operation with no access control
const { data, errors } = keystone.executeGraphQL({ context, query: gql` ... `, variables: { ... }})
```

#### Config

| Option      | Type     | default                    | Description                                             |
| ----------- | -------- | -------------------------- | ------------------------------------------------------- |
| `context`   | `Array`  | `keystone.createContext()` | A `context` object to be used by the GraphQL resolvers. |
| `query`     | `Object` | `undefined`                | The GraphQL operation to execute.                       |
| `variables` | `Object` | `undefined`                | The variables to be passed to the GraphQL operation.    |

---
_Source: https://npm.io/package/@koikorn/keystone · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
