init prisma data model with graphql

master
sundowndev 2019-07-31 15:34:17 +02:00
parent 65e247f0f0
commit 7a47d33fd1
18 changed files with 53812 additions and 1 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

226
README.md
View File

@ -1 +1,225 @@
# interview-v4
# GraphQL Server Example
This example shows how to implement a **GraphQL server with TypeScript** based on Prisma, [graphql-yoga](https://github.com/prisma/graphql-yoga) and [GraphQL Nexus](https://graphql-nexus.com/).
## How to use
### 1. Download example & install dependencies
Clone the repository:
```
git clone git@github.com:prisma/prisma-examples.git
```
Install Node dependencies:
```
cd prisma-examples/typescript/graphql
npm install
```
### 2. Install the Prisma CLI
To run the example, you need the Prisma CLI. Please install it via NPM or [using another method](https://www.prisma.io/docs/prisma-cli-and-configuration/using-the-prisma-cli-alx4/#installation):
```
npm install -g prisma
```
### 3. Set up database & deploy Prisma datamodel
For this example, you'll use a free _demo database_ (AWS Aurora) hosted in Prisma Cloud. To set up your database, run:
```
prisma deploy
```
Then, follow these steps in the interactive CLI wizard:
1. Select **Demo server**
1. **Authenticate** with Prisma Cloud in your browser (if necessary)
1. Back in your terminal, **confirm all suggested values**
<details>
<summary>Alternative: Run Prisma locally via Docker</summary>
1. Ensure you have Docker installed on your machine. If not, you can get it from [here](https://store.docker.com/search?offering=community&type=edition).
1. Create `docker-compose.yml` for MySQL (see [here](https://www.prisma.io/docs/prisma-server/database-connector-POSTGRES-jgfr/) for Postgres):
```yml
version: '3'
services:
prisma:
image: prismagraphql/prisma:1.34
restart: always
ports:
- "4466:4466"
environment:
PRISMA_CONFIG: |
port: 4466
databases:
default:
connector: mysql
host: mysql
port: 3306
user: root
password: prisma
migrations: true
mysql:
image: mysql:5.7
restart: always
environment:
MYSQL_ROOT_PASSWORD: prisma
volumes:
- mysql:/var/lib/mysql
volumes:
mysql:
```
1. Run `docker-compose up -d`
1. Set the `endpoint` in `prisma.yml` to `http://localhost:4466`
1. Run `prisma deploy`
</details>
You can now use [Prisma Admin](https://www.prisma.io/docs/prisma-admin/overview-el3e/) to view and edit your data by appending `/_admin` to your Prisma endpoint.
### 4. Start the GraphQL server
Launch your GraphQL server with this command:
```
npm run start
```
Navigate to [http://localhost:4000](http://localhost:4000) in your browser to explore the API of your GraphQL server in a [GraphQL Playground](https://github.com/prisma/graphql-playground).
### 5. Using the GraphQL API
The schema that specifies the API operations of your GraphQL server is defined in [`./src/schema.graphql`](./src/schema.graphql). Below are a number of operations that you can send to the API using the GraphQL Playground.
Feel free to adjust any operation by adding or removing fields. The GraphQL Playground helps you with its auto-completion and query validation features.
#### Retrieve all published posts and their authors
```graphql
query {
feed {
id
title
content
published
author {
id
name
email
}
}
}
```
<Details><Summary><strong>See more API operations</strong></Summary>
#### Create a new user
```graphql
mutation {
signupUser(
name: "Sarah"
email: "sarah@prisma.io"
) {
id
}
}
```
#### Create a new draft
```graphql
mutation {
createDraft(
title: "Join the Prisma Slack"
content: "https://slack.prisma.io"
authorEmail: "alice@prisma.io"
) {
id
published
}
}
```
#### Publish an existing draft
```graphql
mutation {
publish(id: "__POST_ID__") {
id
published
}
}
```
> **Note**: You need to replace the `__POST_ID__`-placeholder with an actual `id` from a `Post` item. You can find one e.g. using the `filterPosts`-query.
#### Search for posts with a specific title or content
```graphql
{
filterPosts(searchString: "graphql") {
id
title
content
published
author {
id
name
email
}
}
}
```
#### Retrieve a single post
```graphql
{
post(id: "__POST_ID__") {
id
title
content
published
author {
id
name
email
}
}
}
```
> **Note**: You need to replace the `__POST_ID__`-placeholder with an actual `id` from a `Post` item. You can find one e.g. using the `filterPosts`-query.
#### Delete a post
```graphql
mutation {
deletePost(id: "__POST_ID__") {
id
}
}
```
> **Note**: You need to replace the `__POST_ID__`-placeholder with an actual `id` from a `Post` item. You can find one e.g. using the `filterPosts`-query.
</Details>
### 6. Changing the GraphQL schema
To make changes to the GraphQL schema, you need to manipulate the `Query` and `Mutation` types that are defined in [`index.ts`](./src/index.ts).
Note that the [`start`](./package.json#L6) script also starts a development server that automatically updates your schema every time you save a file. This way, the auto-generated [GraphQL schema](./src/generated/schema.graphql) updates whenever you make changes in to the `Query` or `Mutation` types inside your TypeScript code.
## Next steps
- [Use Prisma with an existing database](https://www.prisma.io/docs/-t003/)
- [Explore the Prisma client API](https://www.prisma.io/client/client-typescript)
- [Learn more about the GraphQL schema](https://www.prisma.io/blog/graphql-server-basics-the-schema-ac5e2950214e/)

29
docker-compose.yml Normal file
View File

@ -0,0 +1,29 @@
version: '3'
services:
prisma:
image: prismagraphql/prisma:1.34
restart: on-failure
ports:
- '4466:4466'
environment:
PRISMA_CONFIG: |
port: 4466
databases:
default:
connector: mysql
host: mysql
port: 3306
user: root
password: prisma
migrations: true
mysql:
image: mysql:5.7
restart: on-failure
environment:
MYSQL_ROOT_PASSWORD: prisma
volumes:
- mysql:/var/lib/mysql
volumes:
mysql:

2036
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "typescript-graphql",
"scripts": {
"start": "ts-node-dev --no-notify --respawn --transpileOnly ./src"
},
"dependencies": {
"graphql": "14.4.2",
"graphql-yoga": "1.18.1",
"nexus": "0.11.7",
"nexus-prisma": "0.3.7",
"prisma-client-lib": "1.34.3"
},
"devDependencies": {
"@types/aws-lambda": "8.10.31",
"@types/graphql": "14.2.3",
"@types/node": "10.14.13",
"@types/ws": "6.0.1",
"ts-node-dev": "1.0.0-pre.40",
"typescript": "3.5.3"
}
}

137
prisma/datamodel.prisma Executable file
View File

@ -0,0 +1,137 @@
type Project {
id: ID! @unique @id
clientId: ID @unique
createdAt: DateTime! @createdAt
updatedAt: DateTime! @updatedAt
accounts: [Account!]! @relation(name: "ProjectAccounts", onDelete: CASCADE)
messages: [Message!]! @relation(name: "ProjectMessages", onDelete: CASCADE)
persons: [Person!]! @relation(name: "ProjectPersons", onDelete: CASCADE)
name: String! @unique
}
type Account {
id: ID! @unique @id
clientId: ID @unique
createdAt: DateTime! @createdAt
updatedAt: DateTime! @updatedAt
lastSeenAt: DateTime!
deletedAt: DateTime
project: Project! @relation(name: "ProjectAccounts")
person: Person! @relation(name: "AccountPerson", onDelete: SET_NULL, link: TABLE)
reset_password_token: String
reset_password_exp_date: DateTime
username: String! @unique
hash: String!
need_onboarding: Boolean! @default(value: true)
email_validated: Boolean! @default(value: false)
emailConfirmToken: String
}
enum CHANNEL {
NOTE
INTERCOM
MAIL
SLACK
ZENDESK
SHEET
FORM
}
enum MESSAGE_TYPE {
NOTE
MESSAGE
}
type Submessage {
id: ID! @unique @id
clientId: ID @unique
createdAt: DateTime! @createdAt # date it was created on harvestr
updatedAt: DateTime! @updatedAt
receivedAt: DateTime # real reception date
message: Message! @relation(name: "MessageSubmessages")
submitter: Person!
integration_id: String
type: MESSAGE_TYPE! @default(value: MESSAGE)
content: String! @default(value: "")
}
type Message {
id: ID! @unique @id
clientId: ID @unique
createdAt: DateTime! @createdAt # date it was created on harvestr
updatedAt: DateTime! @updatedAt
receivedAt: DateTime # real reception date
_projectId: ID
project: Project! @relation(name: "ProjectMessages")
sub_messages: [Submessage!]!
@relation(name: "MessageSubmessages", onDelete: CASCADE)
submitter: Person! @relation(name: "MessageSubmitter")
requester: Person @relation(name: "MessageRequester")
ccs: [Person!]! @relation(name: "MessageCcs")
integration_url: String
integration_id: String
title: String! @default(value: "")
content: String! @default(value: "")
channel: CHANNEL! @default(value: NOTE)
read: Boolean! @default(value: false)
updated: Boolean! @default(value: false)
archived: Boolean! @default(value: false)
processed: Boolean! @default(value: false)
}
enum PERSON_TYPE {
COLLABORATOR
CUSTOMER
}
enum RIGHT {
ADMIN
AGENT
VIEWER
}
type ProjectRight {
id: ID! @unique @id
project: Project!
right: RIGHT!
person: Person @relation(name: "PersonRights", link: TABLE)
}
type Person {
id: ID! @unique @id
clientId: ID @unique
createdAt: DateTime! @createdAt
updatedAt: DateTime! @updatedAt
_projectId: ID
project: Project! @relation(name: "ProjectPersons")
right: ProjectRight @relation(name: "PersonRights", onDelete: CASCADE)
submitted_messages: [Message!]! @relation(name: "MessageSubmitter")
requested_messages: [Message!]! @relation(name: "MessageRequester")
cc_messages: [Message!]! @relation(name: "MessageCcs")
account: Account @relation(name: "AccountPerson")
deleted: Boolean! @default(value: false)
type: PERSON_TYPE! @default(value: CUSTOMER)
name: String!
email: String
details: String
phone: String
zendesk_url: String
}

21
prisma/prisma.yml Executable file
View File

@ -0,0 +1,21 @@
# Specifies the HTTP endpoint of your Prisma API.
#endpoint: ''
endpoint: http://localhost:4466
# Defines your models, each model is mapped to the database as a table.
datamodel: datamodel.prisma
# Specifies the language and directory for the generated Prisma client.
generate:
- generator: typescript-client
output: ../src/generated/prisma-client/
# Ensures Prisma client is re-generated after a datamodel change.
hooks:
post-deploy:
- prisma generate
- npx nexus-prisma-generate --client ./src/generated/prisma-client --output ./src/generated/nexus-prisma # Runs the codegen tool from nexus-prisma.
# Seeds initial data into the database by running a script.
seed:
run: yarn ts-node ./prisma/seed.ts

19
prisma/seed.ts Normal file
View File

@ -0,0 +1,19 @@
import { prisma } from '../src/generated/prisma-client';
async function main() {
await prisma.createAccount({
hash: '984896456',
reset_password_token: '984896456',
reset_password_exp_date: Date.now(),
username: 'Alice',
need_onboarding: false,
email_validated: true,
emailConfirmToken: '984896456',
});
await prisma.createProject({
name: 'Coucou',
});
}
main().catch((e) => console.error(e));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
/**
* This file was automatically generated by nexus-prisma@0.3.7
* Do not make changes to this file directly
*/
export { default } from './datamodel-info'

File diff suppressed because it is too large Load Diff

139
src/generated/nexus.ts Executable file
View File

@ -0,0 +1,139 @@
/**
* This file was automatically generated by Nexus 0.11.7
* Do not make changes to this file directly
*/
import * as types from "../types"
declare global {
interface NexusGen extends NexusGenTypes {}
}
export interface NexusGenInputs {
}
export interface NexusGenEnums {
}
export interface NexusGenRootTypes {
Mutation: {};
Post: { // root type
content?: string | null; // String
createdAt: any; // DateTime!
id: string; // ID!
published: boolean; // Boolean!
title: string; // String!
updatedAt: any; // DateTime!
}
Query: {};
User: { // root type
email: string; // String!
id: string; // ID!
name?: string | null; // String
}
String: string;
Int: number;
Float: number;
Boolean: boolean;
ID: string;
DateTime: any;
}
export interface NexusGenAllTypes extends NexusGenRootTypes {
}
export interface NexusGenFieldTypes {
Mutation: { // field return type
createDraft: NexusGenRootTypes['Post'] | null; // Post
deletePost: NexusGenRootTypes['Post'] | null; // Post
publish: NexusGenRootTypes['Post'] | null; // Post
signupUser: NexusGenRootTypes['User'] | null; // User
}
Post: { // field return type
author: NexusGenRootTypes['User']; // User!
content: string | null; // String
createdAt: any; // DateTime!
id: string; // ID!
published: boolean; // Boolean!
title: string; // String!
updatedAt: any; // DateTime!
}
Query: { // field return type
feed: NexusGenRootTypes['Post'][] | null; // [Post!]
filterPosts: NexusGenRootTypes['Post'][] | null; // [Post!]
post: NexusGenRootTypes['Post'] | null; // Post
}
User: { // field return type
email: string; // String!
id: string; // ID!
name: string | null; // String
posts: NexusGenRootTypes['Post'][] | null; // [Post!]
}
}
export interface NexusGenArgTypes {
Mutation: {
createDraft: { // args
authorEmail?: string | null; // String
content?: string | null; // String
title?: string | null; // String
}
deletePost: { // args
id?: string | null; // ID
}
publish: { // args
id?: string | null; // ID
}
signupUser: { // args
email?: string | null; // String
name?: string | null; // String
}
}
Query: {
filterPosts: { // args
searchString?: string | null; // String
}
post: { // args
id?: string | null; // ID
}
}
}
export interface NexusGenAbstractResolveReturnTypes {
}
export interface NexusGenInheritedFields {}
export type NexusGenObjectNames = "Mutation" | "Post" | "Query" | "User";
export type NexusGenInputNames = never;
export type NexusGenEnumNames = never;
export type NexusGenInterfaceNames = never;
export type NexusGenScalarNames = "Boolean" | "DateTime" | "Float" | "ID" | "Int" | "String";
export type NexusGenUnionNames = never;
export interface NexusGenTypes {
context: types.Context;
inputTypes: NexusGenInputs;
rootTypes: NexusGenRootTypes;
argTypes: NexusGenArgTypes;
fieldTypes: NexusGenFieldTypes;
allTypes: NexusGenAllTypes;
inheritedFields: NexusGenInheritedFields;
objectNames: NexusGenObjectNames;
inputNames: NexusGenInputNames;
enumNames: NexusGenEnumNames;
interfaceNames: NexusGenInterfaceNames;
scalarNames: NexusGenScalarNames;
unionNames: NexusGenUnionNames;
allInputTypes: NexusGenTypes['inputNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['scalarNames'];
allOutputTypes: NexusGenTypes['objectNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['unionNames'] | NexusGenTypes['interfaceNames'] | NexusGenTypes['scalarNames'];
allNamedTypes: NexusGenTypes['allInputTypes'] | NexusGenTypes['allOutputTypes']
abstractTypes: NexusGenTypes['interfaceNames'] | NexusGenTypes['unionNames'];
abstractResolveReturn: NexusGenAbstractResolveReturnTypes;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
### This file was autogenerated by Nexus 0.11.7
### Do not make changes to this file directly
scalar DateTime
type Mutation {
createDraft(authorEmail: String, content: String, title: String): Post
deletePost(id: ID): Post
publish(id: ID): Post
signupUser(email: String, name: String): User
}
type Post {
author: User!
content: String
createdAt: DateTime!
id: ID!
published: Boolean!
title: String!
updatedAt: DateTime!
}
type Query {
feed: [Post!]
filterPosts(searchString: String): [Post!]
post(id: ID): Post
}
type User {
email: String!
id: ID!
name: String
posts: [Post!]
}

186
src/index.ts Executable file
View File

@ -0,0 +1,186 @@
import { GraphQLServer } from 'graphql-yoga';
import { idArg, queryType, stringArg } from 'nexus';
import { makePrismaSchema, prismaObjectType } from 'nexus-prisma';
import * as path from 'path';
import datamodelInfo from './generated/nexus-prisma';
import { prisma } from './generated/prisma-client';
const Project = prismaObjectType({
name: 'Project',
definition(t) {
t.prismaFields(['*']);
},
});
const Account = prismaObjectType({
name: 'Account',
definition(t) {
t.prismaFields(['*']);
},
});
const Submessage = prismaObjectType({
name: 'Submessage',
definition(t) {
t.prismaFields(['*']);
},
});
const Message = prismaObjectType({
name: 'Message',
definition(t) {
t.prismaFields(['*']);
},
});
const ProjectRight = prismaObjectType({
name: 'ProjectRight',
definition(t) {
t.prismaFields(['*']);
},
});
const Person = prismaObjectType({
name: 'Person',
definition(t) {
t.prismaFields(['*']);
},
});
const Query = queryType({
definition(t) {
// t.list.field('filterPosts', {
// type: 'Post',
// args: {
// searchString: stringArg({ nullable: true }),
// },
// resolve: (parent, { searchString }, ctx) => {
// return ctx.prisma.posts({
// where: {
// OR: [
// { title_contains: searchString },
// { content_contains: searchString },
// ],
// },
// });
// },
// });
// t.field('post', {
// type: 'Post',
// nullable: true,
// args: { id: idArg() },
// resolve: (parent, { id }, ctx) => {
// return ctx.prisma.post({ id });
// },
// });
},
});
const Mutation = prismaObjectType({
name: 'Mutation',
definition(t) {
// t.field('signupUser', {
// type: 'User',
// args: {
// name: stringArg({ nullable: true }),
// email: stringArg(),
// },
// resolve: (parent, { name, email }, ctx) => {
// return ctx.prisma.createUser({
// name,
// email,
// });
// },
// });
// t.field('createDraft', {
// type: 'Post',
// args: {
// title: stringArg(),
// content: stringArg({ nullable: true }),
// authorEmail: stringArg(),
// },
// resolve: (parent, { title, content, authorEmail }, ctx) => {
// return ctx.prisma.createPost({
// title,
// content,
// author: {
// connect: { email: authorEmail },
// },
// });
// },
// });
// t.field('deletePost', {
// type: 'Post',
// nullable: true,
// args: {
// id: idArg(),
// },
// resolve: (parent, { id }, ctx) => {
// return ctx.prisma.deletePost({ id });
// },
// });
// t.field('publish', {
// type: 'Post',
// nullable: true,
// args: {
// id: idArg(),
// },
// resolve: (parent, { id }, ctx) => {
// return ctx.prisma.updatePost({
// where: { id },
// data: { published: true },
// });
// },
// });
},
});
const schema = makePrismaSchema({
// Provide all the GraphQL types we've implemented
types: [
Query,
Mutation,
Project,
Account,
Submessage,
Message,
ProjectRight,
Person,
],
// Configure the interface to Prisma
prisma: {
datamodelInfo,
client: prisma,
},
// Specify where Nexus should put the generated files
outputs: {
schema: path.join(__dirname, './generated/schema.graphql'),
typegen: path.join(__dirname, './generated/nexus.ts'),
},
// Configure nullability of input arguments: All arguments are non-nullable by default
nonNullDefaults: {
input: false,
output: false,
},
// Configure automatic type resolution for the TS representations of the associated types
typegenAutoConfig: {
sources: [
{
source: path.join(__dirname, './types.ts'),
alias: 'types',
},
],
contextType: 'types.Context',
},
});
const server = new GraphQLServer({
schema,
context: { prisma },
});
server.start(() => console.log(`🚀 Server ready at http://localhost:4000`));

5
src/types.ts Executable file
View File

@ -0,0 +1,5 @@
import { Prisma } from './generated/prisma-client'
export interface Context {
prisma: Prisma
}

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"lib": ["esnext", "dom"],
// "strict": true, // `strict` is commented because of this issue: https://github.com/prisma/prisma/issues/3774; all its options except `strictNullChecks` & `strictPropertyInitialization` are explicitly set below.
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true,
"strictBindCallApply": true,
"strictFunctionTypes": true,
"skipLibCheck": true // `skipLibCheck` is enabled until this is issue is fixed: https://github.com/prisma/nexus-prisma/issues/82
}
}