Skip to content

Commit

Permalink
Add new getContext function and script example (#7954)
Browse files Browse the repository at this point in the history
* add getContext

* yarn format

* add comments

Co-authored-by: Daniel Cousens <dcousens@users.noreply.github.com>
  • Loading branch information
dcousens and dcousens committed Sep 26, 2022
1 parent 6497e1c commit c75340f
Show file tree
Hide file tree
Showing 8 changed files with 325 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/binary-eats-wilderberries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystone-6/core': minor
---

Adds new `getContext` function for working with a Keystone configuration directly
31 changes: 31 additions & 0 deletions examples/script/keystone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { config, list } from '@keystone-6/core';
import { allowAll } from '@keystone-6/core/access';
import { text, timestamp } from '@keystone-6/core/fields';
import { TypeInfo } from '.keystone/types';

export default config<TypeInfo>({
db: {
provider: 'sqlite',
url: process.env.DATABASE_URL || 'file:./keystone-example.db',

// this is called by Keystone on start, or when connect() is called in script.ts
onConnect: async context => {
console.log('(keystone.ts)', 'onConnect');
await context.db.Post.createOne({ data: { title: 'Created in onConnect' } });
},
},
lists: {
Post: list({
access: allowAll,
fields: {
title: text(),
createdAt: timestamp({
db: {
isNullable: false,
},
defaultValue: { kind: 'now' },
}),
},
}),
},
});
19 changes: 19 additions & 0 deletions examples/script/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@keystone-6/example-script",
"version": "0.0.1",
"private": true,
"license": "MIT",
"scripts": {
"dev": "keystone dev",
"start": "keystone start",
"build": "keystone build"
},
"dependencies": {
"@keystone-6/core": "^2.2.0"
},
"devDependencies": {
"tsx": "^3.9.0",
"typescript": "~4.7.4"
},
"repository": "https://github.com/keystonejs/keystone/tree/main/examples/script"
}
207 changes: 207 additions & 0 deletions examples/script/schema.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
# This file is automatically generated by Keystone, do not modify it manually.
# Modify your Keystone config when you want to change this.

type Post {
id: ID!
title: String
createdAt: DateTime
}

scalar DateTime @specifiedBy(url: "https://datatracker.ietf.org/doc/html/rfc3339#section-5.6")

input PostWhereUniqueInput {
id: ID
}

input PostWhereInput {
AND: [PostWhereInput!]
OR: [PostWhereInput!]
NOT: [PostWhereInput!]
id: IDFilter
title: StringFilter
createdAt: DateTimeFilter
}

input IDFilter {
equals: ID
in: [ID!]
notIn: [ID!]
lt: ID
lte: ID
gt: ID
gte: ID
not: IDFilter
}

input StringFilter {
equals: String
in: [String!]
notIn: [String!]
lt: String
lte: String
gt: String
gte: String
contains: String
startsWith: String
endsWith: String
not: NestedStringFilter
}

input NestedStringFilter {
equals: String
in: [String!]
notIn: [String!]
lt: String
lte: String
gt: String
gte: String
contains: String
startsWith: String
endsWith: String
not: NestedStringFilter
}

input DateTimeFilter {
equals: DateTime
in: [DateTime!]
notIn: [DateTime!]
lt: DateTime
lte: DateTime
gt: DateTime
gte: DateTime
not: DateTimeFilter
}

input PostOrderByInput {
id: OrderDirection
title: OrderDirection
createdAt: OrderDirection
}

enum OrderDirection {
asc
desc
}

input PostUpdateInput {
title: String
createdAt: DateTime
}

input PostUpdateArgs {
where: PostWhereUniqueInput!
data: PostUpdateInput!
}

input PostCreateInput {
title: String
createdAt: DateTime
}

"""
The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSON @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")

type Mutation {
createPost(data: PostCreateInput!): Post
createPosts(data: [PostCreateInput!]!): [Post]
updatePost(where: PostWhereUniqueInput!, data: PostUpdateInput!): Post
updatePosts(data: [PostUpdateArgs!]!): [Post]
deletePost(where: PostWhereUniqueInput!): Post
deletePosts(where: [PostWhereUniqueInput!]!): [Post]
}

type Query {
posts(where: PostWhereInput! = {}, orderBy: [PostOrderByInput!]! = [], take: Int, skip: Int! = 0): [Post!]
post(where: PostWhereUniqueInput!): Post
postsCount(where: PostWhereInput! = {}): Int
keystone: KeystoneMeta!
}

type KeystoneMeta {
adminMeta: KeystoneAdminMeta!
}

type KeystoneAdminMeta {
lists: [KeystoneAdminUIListMeta!]!
list(key: String!): KeystoneAdminUIListMeta
}

type KeystoneAdminUIListMeta {
key: String!
itemQueryName: String!
listQueryName: String!
hideCreate: Boolean!
hideDelete: Boolean!
path: String!
label: String!
singular: String!
plural: String!
description: String
initialColumns: [String!]!
pageSize: Int!
labelField: String!
fields: [KeystoneAdminUIFieldMeta!]!
initialSort: KeystoneAdminUISort
isHidden: Boolean!
isSingleton: Boolean
}

type KeystoneAdminUIFieldMeta {
path: String!
label: String!
description: String
isOrderable: Boolean!
isFilterable: Boolean!
fieldMeta: JSON
viewsIndex: Int!
customViewsIndex: Int
createView: KeystoneAdminUIFieldMetaCreateView!
listView: KeystoneAdminUIFieldMetaListView!
itemView(id: ID): KeystoneAdminUIFieldMetaItemView
search: QueryMode
}

type KeystoneAdminUIFieldMetaCreateView {
fieldMode: KeystoneAdminUIFieldMetaCreateViewFieldMode!
}

enum KeystoneAdminUIFieldMetaCreateViewFieldMode {
edit
hidden
}

type KeystoneAdminUIFieldMetaListView {
fieldMode: KeystoneAdminUIFieldMetaListViewFieldMode!
}

enum KeystoneAdminUIFieldMetaListViewFieldMode {
read
hidden
}

type KeystoneAdminUIFieldMetaItemView {
fieldMode: KeystoneAdminUIFieldMetaItemViewFieldMode
}

enum KeystoneAdminUIFieldMetaItemViewFieldMode {
edit
read
hidden
}

enum QueryMode {
default
insensitive
}

type KeystoneAdminUISort {
field: String!
direction: KeystoneAdminUISortDirection!
}

enum KeystoneAdminUISortDirection {
ASC
DESC
}
19 changes: 19 additions & 0 deletions examples/script/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// This file is automatically generated by Keystone, do not modify it manually.
// Modify your Keystone config when you want to change this.

datasource sqlite {
url = env("DATABASE_URL")
shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
provider = "sqlite"
}

generator client {
provider = "prisma-client-js"
output = "node_modules/.prisma/client"
}

model Post {
id String @id @default(cuid())
title String @default("")
createdAt DateTime @default(now())
}
24 changes: 24 additions & 0 deletions examples/script/script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { getContext } from '@keystone-6/core/system';
import config from './keystone';
import * as PrismaModule from '.prisma/client';

async function main() {
const { connect, context, disconnect } = getContext(config, PrismaModule);

console.log('(script.ts)', 'connect');

// if you don't call connect here, db.onConnect will not be run
// but, Prisma will automatically connect whenever Prisma is used
await connect();

const run = (Math.random() * 1e5) | 0;
for (let i = 0; i < 10; ++i) {
console.log('(script.ts)', `Post.createOne ${i}`);
await context.db.Post.createOne({ data: { title: `Post #${i}, run ${run}` } });
}

console.log('(script.ts)', 'disconnect');
await disconnect();
}

main();
19 changes: 19 additions & 0 deletions packages/core/src/lib/getContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { createSystem, initConfig } from '../system';
import { BaseKeystoneTypeInfo, KeystoneConfig, KeystoneContext } from '../types';

export function getContext<TypeInfo extends BaseKeystoneTypeInfo>(
config: KeystoneConfig<TypeInfo>,
PrismaModule: unknown
): {
context: KeystoneContext<TypeInfo>;
connect: () => Promise<void>;
disconnect: () => Promise<void>;
} {
const system = createSystem(initConfig(config));
const { connect, createContext, disconnect } = system.getKeystone(PrismaModule as any);
return {
context: createContext(),
connect,
disconnect,
};
}
1 change: 1 addition & 0 deletions packages/core/src/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export { createExpressServer } from './lib/server/createExpressServer';
export { createAdminUIMiddleware } from './lib/server/createAdminUIMiddleware';
export { initConfig } from './lib/config/initConfig';
export { createApolloServerMicro } from './lib/server/createApolloServer';
export { getContext } from './lib/getContext';

1 comment on commit c75340f

@vercel
Copy link

@vercel vercel bot commented on c75340f Sep 26, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.