Giter Club home page Giter Club logo

graphql-prisma-typescript's Introduction

Airbnb Clone - GraphQL Server Example with Prisma

This project demonstrates how to build a production-ready application with Prisma and graphql-yoga. The API provided by the GraphQL server is the foundation for an application similar to AirBnB.

Get started

Note: prisma is listed as a development dependency and script in this project's package.json. This means you can invoke the Prisma CLI without having it globally installed on your machine (by prefixing it with yarn), e.g. yarn prisma deploy or yarn prisma playground. If you have the Prisma CLI installed globally (which you can do with npm install -g prisma), you can omit the yarn prefix.

1. Download the example & install dependencies

Clone the repository with the following command:

git clone [email protected]:graphcool/graphql-server-example.git

Next, navigate into the downloaded folder and install the NPM dependencies:

cd graphql-server-example
yarn install

2. Deploy the Prisma database service

You can now deploy the Prisma service (note that this requires you to have Docker installed on your machine - if that's not the case, follow the collapsed instructions below the code block):

cd prisma
docker-compose up -d
cd ..
yarn prisma deploy
I don't have Docker installed on my machine

To deploy your service to a public cluster (rather than locally with Docker), you need to perform the following steps:

  1. Remove the cluster property from prisma.yml.
  2. Run yarn prisma deploy.
  3. When prompted by the CLI, select a public cluster (e.g. prisma-eu1 or prisma-us1).
  4. Replace the endpoint in index.ts with the HTTP endpoint that was printed after the previous command.

Notice that when deploying the Prisma service for the very first time, the CLI will execute the mutations from prisma/seed.graphql to seed some initial data in the database. The CLI is aware of this file because it's listed in prisma/prisma.yml under the seed property.

3. Start the GraphQL server

The Prisma database service that's backing your GraphQL server is now available. This means you can now start the server:

yarn dev

The dev script starts the server (on http://localhost:4000) and opens a GraphQL Playground where you get acces to the API of your GraphQL server (defined in the application schema) as well as the underlying Prisma API (defined in the auto-generated Prisma database schema) directly.

Inside the Playground, you can start exploring the available operations by browsing the built-in documentation.

Testing the API

Check queries/booking.graphql and queries/queries.graphql to see several example operations you can send to the API. To get an understanding of the booking flows, check the mutations in queries/booking.graphql.

Deployment

A quick and easy way to deploy the GraphQL server from this repository is with Zeit Now. After you downloaded the Now Desktop app, you can deploy the server with the following command:

now --dotenv .env.prod

Notice that you need to create the .env.prod file yourself before invoking the command. It should list the same environment variables as .env but with different values. In particular, you need to make sure that your Prisma service is deployed to a cluster that accessible over the web.

Here is an example for what .env.prod might look like:

PRISMA_STAGE="prod"
PRISMA_CLUSTER="public-tundrapiper-423/prisma-us1"
PRISMA_ENDPOINT="http://us1.prisma.sh/public-tundrapiper-423/prisma-airbnb-example/dev"
PRISMA_SECRET="mysecret123"
APP_SECRET="appsecret321"

To learn more about deploying GraphQL servers with Zeit Now, check out this tutorial.

Troubleshooting

I'm getting the error message [Network error]: FetchError: request to http://localhost:4466/auth-example/dev failed, reason: connect ECONNREFUSED when trying to send a query or mutation

This is because the endpoint for the Prisma service is hardcoded in index.js. The service is assumed to be running on the default port for a local cluster: http://localhost:4466. Apparently, your local cluster is using a different port.

You now have two options:

  1. Figure out the port of your local cluster and adjust it in index.js. You can look it up in ~/.prisma/config.yml.
  2. Deploy the service to a public cluster. Expand the I don't have Docker installed on my machine-section in step 2 for instructions.

Either way, you need to adjust the endpoint that's passed to the Prisma constructor in index.js so it reflects the actual cluster domain and service endpoint.

License

MIT

graphql-prisma-typescript's People

Contributors

abhiaiyer91 avatar amilajack avatar c-riq avatar caub avatar davidjfelix avatar devanb avatar djmetzle avatar dpetrick avatar giautm avatar kbrandwijk avatar marktani avatar nikolasburk avatar renovate-bot avatar renovate[bot] avatar schickling avatar sorenbs avatar timsuchanek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-prisma-typescript's Issues

"Your token is invalid"

After following the instructions in the readme, I have the Prisma server up and running in docker. When I visit http://192.168.99.100:4466/example-airbnb/dev as suggested, and before I attempt any queries, I see the following error:

{
  "code": 3015,
  "requestId": "api:api:cjcsxgg0s00690187qqxn3kzk",
  "error": "Your token is invalid. It might have expired or you might be using a token from a different project."
}

Provide better error message for refused connection

Error: request to http://localhost:60000/api/example-airbnb/dev failed, reason: connect ECONNREFUSED
127.0.0.1:60000
    at Object.checkResultAndHandleErrors (/Users/marktani/projects/playground/beta-1.1/graphcool-serv
er-example/node_modules/graphql-tools/src/stitching/errors.ts:84:7)
    at Object.<anonymous> (/Users/marktani/projects/playground/beta-1.1/graphcool-server-example/node
_modules/graphql-tools/src/stitching/delegateToSchema.ts:91:14)
    at step (/Users/marktani/projects/playground/beta-1.1/graphcool-server-example/node_modules/graph
ql-tools/dist/stitching/delegateToSchema.js:40:23)
    at Object.next (/Users/marktani/projects/playground/beta-1.1/graphcool-server-example/node_module
s/graphql-tools/dist/stitching/delegateToSchema.js:21:53)
    at fulfilled (/Users/marktani/projects/playground/beta-1.1/graphcool-server-example/node_modules/
graphql-tools/dist/stitching/delegateToSchema.js:12:58)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)

My localdatabase_graphcool-database_1 container is on port 60001 and not 60000. We could return an error like

Error: request to http://localhost:60000/api/example-airbnb/dev failed, this is probably because your docker container localdatabase_graphcool-database_1 is not running on port 60000. Run docker ps to find out the port and update .env accordingly.

Example Prisma API

Might be helpful to have an example GraphQL Playground linked from the Prisma homepage, to show what a generated Prisma endpoint looks like, with filtering, sorting, pagination. More hands on than reading through https://www.prismagraphql.com/docs/reference/prisma-api/queries-ahwee4zaey

When deciding whether I'm going to use something, I want to see/interact with the API. Eg with Firebase, I had to go through all the possible queries to realize that it wasn't powerful enough to do the queries my app required, so I had to build my own indexes with it.

Subselection not recognized

I added this property to Home in https://github.com/graphcool/graphcool-server-example/blob/master/src/resolvers/Home.ts

perNight: {
    resolve: async ({ id }, args, ctx: Context, info) => {
      const place = await ctx.db.query.place({ where: { id } },"{ pricing { perNight } }")
      return place.pricing.perNight
    },
},

And perNight: Int! to the Home type in schema.graphql

Then running this query in the playground

{
  topHomes {
    perNight
  }
}

returns the error

"Field 'places' of type 'Place' must have a sub selection. (line 2, column 3):\n  places(where: $_where, orderBy: $_orderBy, skip: $_skip, after: $_after, before: $_before, first: $_first, last: $_last)\n  ^"

but this query works as expected

{
  topHomes {
    perNight
    id
  }
}

Now deployment fails at rm -rf dist && graphql prepare && tsc

When I run
yarn deploy

I get the following error on now:

 > [email protected] build /home/nowuser/src
> > rm -rf dist && graphql prepare && tsc
> ✔ Bindings for project database written to src/generated/prisma.ts
> node_modules/@types/zen-observable/index.d.ts(31,14): error TS2300: Duplicate identifier 'Subscriber'.
> npm ERR! code ELIFECYCLE
> npm ERR! errno 2
> npm ERR! [email protected] build: `rm -rf dist && graphql prepare && tsc`
> npm ERR! Exit status 2
> npm ERR! 
> npm ERR! Failed at the [email protected] build script.
> npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
> npm ERR! A complete log of this run can be found in:
> npm ERR!     /home/nowuser/.npm/_logs/2018-01-21T22_20_20_783Z-debug.log
> Error! The build step of your project failed. To retry, run `now --force`.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

update README

  • it doesn't contain information on getting started (install graphql-cli/graphcool)
  • it should list a few example queries and mutations

Currently, it's difficult to know what do to.

A common error I saw is running writePost as your first operation, and mistakenly use a JWT that was signed with GRAPHCOOL_SECRET instead of the JWT_SECRET. In this case, the error message

{
  "data": null,
  "errors": [
    {
      "message": "invalid signature",
      "locations": [
        {
          "line": 1,
          "column": 10
        }
      ],
      "path": [
        "writePost"
      ]
    }
  ]
}

is not helpful.

Resolver for `addPaymentMethod` doesn't transform input arguments

https://github.com/graphcool/graphql-server-example/blob/7b86ad6c761eee0d37a7f2bc419ddcef2a1499cc/src/resolvers/Mutation/addPaymentMethod.ts#L12

This passes in the arguments 'as is' to the underlying createPaymentAccount mutation, but that mutation requires { userId: ID!, creditcard: PaymentAccountcreditcardCreditCardInformation }

I believe this line needs to be changed to { creditcard: args, userId }.

In the current version, the mutation fails because of this.

ERROR: Whoops, Looks like an internal server error

Getting error when prisma deploy

Creating stage default for service default !

ERROR: Whoops. Looks like an internal server error. Search your server logs for request ID: local:management:cjj8ok4ey000208461zdt8zte

{
  "data": {
    "addProject": null
  },
  "errors": [
    {
      "message": "Whoops. Looks like an internal server error. Search your server logs for request ID: local:management:cjj8ok4ey000208461zdt8zte",
      "path": [
        "addProject"
      ],
      "locations": [
        {
          "line": 2,
          "column": 9
        }
      ],
      "requestId": "local:management:cjj8ok4ey000208461zdt8zte"
    }
  ],
  "status": 200
}

Tried also prisma local nuke. But error showing continuously.

UPDATE: my docker-compose logs is showing:

prisma_1  | Obtaining exclusive agent lock...
prisma_1  | Obtaining exclusive agent lock... Successful.
prisma_1  | Deployment worker initialization complete.
prisma_1  | Initializing workers...
prisma_1  | Successfully started 1 workers.
prisma_1  | Server running on :4466
prisma_1  | Version is up to date.
prisma_1  | [Metrics] Warning: no metrics will be recorded.
prisma_1  | Warning: Management API authentication is disabled. To protect your management server you should provide one (not both) of the environment variables 'CLUSTER_PUBLIC_KEY' (asymmetric, deprecated soon) or 'PRISMA_MANAGEMENT_API_JWT_SECRET' (symmetric JWT).
prisma_1  | {"key":"error/handled","requestId":"local:management:cjj8ok48y000108460bcizs3r","payload":{"exception":"com.prisma.deploy.schema.InvalidProjectId: No service with name 'default' and stage 'default' found","query":"\n      query($name: String! $stage: String!) {\n        project(name: $name stage: $stage) {\n          name\n          stage\n        }\n      }\n    ","variables":"{\"name\":\"default\",\"stage\":\"default\"}","code":"4000","stack_trace":"com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$3(SchemaBuilder.scala:139)\\n scala.Option.getOrElse(Option.scala:121)\\n com.prisma.deploy.schema.SchemaBuilderImpl.$anonfun$projectField$2(SchemaBuilder.scala:139)\\n scala.util.Success.$anonfun$map$1(Try.scala:251)\\n scala.util.Success.map(Try.scala:209)\\n scala.concurrent.Future.$anonfun$map$1(Future.scala:287)\\n scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)\\n scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)\\n scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)\\n akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)\\n akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:91)\\n scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)\\n scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)\\n akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:91)\\n akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)\\n akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:43)\\n akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)\\n akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)\\n akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)\\n akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)","message":"No service with name 'default' and stage 'default' found"}}
prisma_1  | Warning: Management API authentication is disabled. To protect your management server you should provide one (not both) of the environment variables 'CLUSTER_PUBLIC_KEY' (asymmetric, deprecated soon) or 'PRISMA_MANAGEMENT_API_JWT_SECRET' (symmetric JWT).
prisma_1  | java.sql.SQLIntegrityConstraintViolationException: (conn=273) Duplicate entry 'default@default' for key 'PRIMARY'
prisma_1  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:157)
prisma_1  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:106)
prisma_1  |     at org.mariadb.jdbc.MariaDbStatement.executeExceptionEpilogue(MariaDbStatement.java:235)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeInternal(MariaDbPreparedStatementClient.java:224)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.execute(MariaDbPreparedStatementClient.java:159)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeUpdate(MariaDbPreparedStatementClient.java:192)
prisma_1  |     at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
prisma_1  |     at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
prisma_1  |     at slick.jdbc.JdbcActionComponent$InsertActionComposerImpl$SingleInsertAction.$anonfun$run$11(JdbcActionComponent.scala:511)
prisma_1  |     at slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement(JdbcBackend.scala:372)
prisma_1  |     at slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement$(JdbcBackend.scala:367)
prisma_1  |     at slick.jdbc.JdbcBackend$BaseSession.withPreparedStatement(JdbcBackend.scala:434)
prisma_1  |     at slick.jdbc.JdbcActionComponent$InsertActionComposerImpl.preparedInsert(JdbcActionComponent.scala:502)
prisma_1  |     at slick.jdbc.JdbcActionComponent$InsertActionComposerImpl$SingleInsertAction.run(JdbcActionComponent.scala:508)
prisma_1  |     at slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:31)
prisma_1  |     at slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:28)
prisma_1  |     at slick.basic.BasicBackend$DatabaseDef$$anon$2.liftedTree1$1(BasicBackend.scala:240)
prisma_1  |     at slick.basic.BasicBackend$DatabaseDef$$anon$2.run(BasicBackend.scala:240)
prisma_1  |     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
prisma_1  |     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
prisma_1  |     at java.lang.Thread.run(Thread.java:748)
prisma_1  | Caused by: java.sql.SQLException: Duplicate entry 'default@default' for key 'PRIMARY'
prisma_1  | Query is: insert into `Project` (`id`,`webhookUrl`,`ownerId`,`secrets`,`allowQueries`,`allowMutations`,`functions`)  values (?,?,?,?,?,?,?), parameters ['default@default','',<null>,'[]',1,1,'[]']
prisma_1  |     at org.mariadb.jdbc.internal.util.LogQueryTool.exceptionWithQuery(LogQueryTool.java:146)
prisma_1  |     at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:217)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeInternal(MariaDbPreparedStatementClient.java:218)
prisma_1  |     ... 17 more
prisma_1  | {"key":"error/unhandled","requestId":"local:management:cjj8ok4ey000208461zdt8zte","payload":{"exception":"java.sql.SQLIntegrityConstraintViolationException: (conn=273) Duplicate entry 'default@default' for key 'PRIMARY'","query":"      mutation addProject($name: String! $stage: String! $secrets: [String!]) {\n        addProject(input: {\n          name: $name,\n          stage: $stage\n          secrets: $secrets\n        }) {\n          project {\n            name\n          }\n        }\n      }\n      ","variables":"{\"name\":\"default\",\"stage\":\"default\",\"secrets\":null}","code":"0","stack_trace":"org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:157)\\n org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:106)\\n org.mariadb.jdbc.MariaDbStatement.executeExceptionEpilogue(MariaDbStatement.java:235)\\n org.mariadb.jdbc.MariaDbPreparedStatementClient.executeInternal(MariaDbPreparedStatementClient.java:224)\\n org.mariadb.jdbc.MariaDbPreparedStatementClient.execute(MariaDbPreparedStatementClient.java:159)\\n org.mariadb.jdbc.MariaDbPreparedStatementClient.executeUpdate(MariaDbPreparedStatementClient.java:192)\\n com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)\\n com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)\\n slick.jdbc.JdbcActionComponent$InsertActionComposerImpl$SingleInsertAction.$anonfun$run$11(JdbcActionComponent.scala:511)\\n slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement(JdbcBackend.scala:372)\\n slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement$(JdbcBackend.scala:367)\\n slick.jdbc.JdbcBackend$BaseSession.withPreparedStatement(JdbcBackend.scala:434)\\n slick.jdbc.JdbcActionComponent$InsertActionComposerImpl.preparedInsert(JdbcActionComponent.scala:502)\\n slick.jdbc.JdbcActionComponent$InsertActionComposerImpl$SingleInsertAction.run(JdbcActionComponent.scala:508)\\n slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:31)\\n slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:28)\\n slick.basic.BasicBackend$DatabaseDef$$anon$2.liftedTree1$1(BasicBackend.scala:240)\\n slick.basic.BasicBackend$DatabaseDef$$anon$2.run(BasicBackend.scala:240)\\n java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\\n java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\\n java.lang.Thread.run(Thread.java:748)","message":"(conn=273) Duplicate entry 'default@default' for key 'PRIMARY'"}}
prisma_1  | [Bugsnag - local / testing] Error report: com.bugsnag.Report@5b975ba9
prisma_1  | java.sql.SQLIntegrityConstraintViolationException: (conn=273) Duplicate entry 'default@default' for key 'PRIMARY'
prisma_1  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:157)
prisma_1  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:106)
prisma_1  |     at org.mariadb.jdbc.MariaDbStatement.executeExceptionEpilogue(MariaDbStatement.java:235)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeInternal(MariaDbPreparedStatementClient.java:224)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.execute(MariaDbPreparedStatementClient.java:159)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeUpdate(MariaDbPreparedStatementClient.java:192)
prisma_1  |     at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
prisma_1  |     at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
prisma_1  |     at slick.jdbc.JdbcActionComponent$InsertActionComposerImpl$SingleInsertAction.$anonfun$run$11(JdbcActionComponent.scala:511)
prisma_1  |     at slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement(JdbcBackend.scala:372)
prisma_1  |     at slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement$(JdbcBackend.scala:367)
prisma_1  |     at slick.jdbc.JdbcBackend$BaseSession.withPreparedStatement(JdbcBackend.scala:434)
prisma_1  |     at slick.jdbc.JdbcActionComponent$InsertActionComposerImpl.preparedInsert(JdbcActionComponent.scala:502)
prisma_1  |     at slick.jdbc.JdbcActionComponent$InsertActionComposerImpl$SingleInsertAction.run(JdbcActionComponent.scala:508)
prisma_1  |     at slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:31)
prisma_1  |     at slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:28)
prisma_1  |     at slick.basic.BasicBackend$DatabaseDef$$anon$2.liftedTree1$1(BasicBackend.scala:240)
prisma_1  |     at slick.basic.BasicBackend$DatabaseDef$$anon$2.run(BasicBackend.scala:240)
prisma_1  |     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
prisma_1  |     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
prisma_1  |     at java.lang.Thread.run(Thread.java:748)
prisma_1  | Caused by: java.sql.SQLException: Duplicate entry 'default@default' for key 'PRIMARY'
prisma_1  | Query is: insert into `Project` (`id`,`webhookUrl`,`ownerId`,`secrets`,`allowQueries`,`allowMutations`,`functions`)  values (?,?,?,?,?,?,?), parameters ['default@default','',<null>,'[]',1,1,'[]']
prisma_1  |     at org.mariadb.jdbc.internal.util.LogQueryTool.exceptionWithQuery(LogQueryTool.java:146)
prisma_1  |     at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:217)
prisma_1  |     at org.mariadb.jdbc.MariaDbPreparedStatementClient.executeInternal(MariaDbPreparedStatementClient.java:218)
prisma_1  |     ... 17 more

yarn seed doesn't work

$ yarn seed
yarn run v1.3.2
$ dotenv -- graphql query database/seed.graphql --all -p database
You don't have any enpoint in your .graphqlconfig.
Run graphql add-endpoint to add endpoint to your config
Done in 3.12s.
projects:
  app:
    schemaPath: "src/schema.generated.graphql"
    includes: ["queries/{booking,queries}.graphql"]
    extensions:
      endpoints:
        default: "http://localhost:5000"
  database:
    schemaPath: "database/schema.graphql"
    includes: ["database/seed.graphql"]
    extensions:
      graphcool: graphcool.yml

Demo server (https://airbnb.now.sh/) is broken

I tried to execute the following query:

{
  topExperiences {
    title
  }
}

And got this error:

{
  "data": null,
  "errors": [
    {
      "message": "request to https://prisma-eu1.prisma.sh/demo/example-airbnb/prod failed, reason: getaddrinfo ENOTFOUND prisma-eu1.prisma.sh prisma-eu1.prisma.sh:443",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "topExperiences"
      ]
    }
  ]
}

Playground URL: https://www.graphqlbin.com/v27EFW (don't work for me)

Custom resolvers are degrading performance dramatically.

I have hosted this repo and I found a pretty big performance issue I mentioned to @marktani over Slack. He then told me to make an issue.

https://entr-server.now.sh/
This is pretty much the same code, with a few custom resolvers added.

Prisma is hosted on the US shared cluster.
Graphql server is hosted on now.sh.

If you send the following query to the playground, you will notice things are fast as I am expecting:

Test 1

Query

query {
  spaces {
    id
  }
}

Performance:

screenshot 2018-01-22 17 58 33

Now let's add a custom resolver from this repo, numRatings, basically this :

Test 2

Query

query {
  spaces {
    id
    numRatings
  }
}

Performance:

screenshot 2018-01-22 18 01 00

All of a sudden this query takes over 7 seconds 😱

Test 3

Now let's add another one. I made this one myself:

Query

query {
  spaces {
    id
    numRatings
    avgRating
  }
}

Performance

screenshot 2018-01-22 18 02 44

It pretty much exactly doubled.

What's going on here? Can someone please explain how custom revolvers impact performance? Would love to learn more

Everything can be tested on
https://entr-server.now.sh/

Thank you very much :)

Direnv doesn't work well on Windows

I noticed the addition of .envrc. It really doesn't work well on Windows, if at all. Could I convince you to switch to dotenv, which works very well cross-platform?

Error on Git Clone

 git clone [email protected]:graphcool/graphql-server-example.git
Cloning into 'graphql-server-example'...
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Command error: "yarn prisma deploy"

yarn prisma deploy
yarn run v1.5.1
$ prisma deploy
warning prisma.yml: "cluster", "service" and "stage" are deprecated and will be replaced with "endpoint".
To get the endpoint, run prisma info. Read more here: https://bit.ly/migrate-prisma-yml

Creating stage dev for service prisma-airbnb-example !

ERROR: GraphQL Error (Code: 405)

{
"error": "HTTP method not allowed, supported methods: GET",
"status": 405
}

Get in touch if you need help: https://www.graph.cool/forum
To get more detailed output, run $ export DEBUG="*"
Done in 14.54s.

ERROR: Whoops. Looks like an internal server error.

yarn prisma deploy

ERROR: Whoops. Looks like an internal server error. Search your cluster logs for request ID: cluster:cluster:cjck2cdwu0007015057b7x7tw

{ "data": { "addProject": null }, "errors": [ { "message": "Whoops. Looks like an internal server error. Search your cluster logs for request ID: cluster:cluster:cjck2cdwu0007015057b7x7tw", "path": [ "addProject" ], "locations": [ { "line": 2, "column": 9 } ], "requestId": "cluster:cluster:cjck2cdwu0007015057b7x7tw" } ], "status": 200 }

Examples leak data - i can see what other users booked - or is this on purpose?

For example, if i have a booking, i can see who else booked the same place and when. I can fetch their email, personal data etc.

{
  viewer {
    me {
      lastName
    }
    bookings {
      place {
        name
        bookings {
        	bookee {
            firstName
            lastName
            email
          }
        }
      }
    }
  }
}

Response

{
  "data": {
    "viewer": {
      "me": {
        "lastName": "Smith"
      },
      "bookings": [
        {
          "place": {
            "name": "Mushroom Dome Cabin: #1 on airbnb in the world",
            "bookings": [
              {
                "bookee": {
                  "firstName": "Karl",
                  "lastName": "Marx",
                  "email": "[email protected]"
                }
              },
              {
                "bookee": {
                  "firstName": "Adam",
                  "lastName": "Smith",
                  "email": "[email protected]"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Hmm interesting, Karl will also be at Mushroom Dome!

This is a problem i ran into, not only in this server example, but also in my own and other peoples server code. As soon as we have cyclic model references, hiding data becomes very complex.

There is some bug preventing from generating bindings for app itself

Steps to reproduce

Modify .graphqlconfig.yml to:

projects:
  app:
    schemaPath: "src/schema.graphql"
    includes: ["queries/{booking,queries}.graphql"]
    extensions:
      prepare-bundle: src/generated/app.graphql
      endpoints:
        default: "http://localhost:5000"
        prepare-bundle: src/generated/app.graphql
      prepare-binding:
        output: src/generated/app.ts
        generator: graphcool-ts
  database:
    schemaPath: "src/generated/database.graphql"
    includes: ["database/seed.graphql"]
    extensions:
      graphcool: graphcool.yml
      prepare-binding:
        output: src/generated/graphcool.ts
        generator: graphcool-ts

Run yarn prepare

Expected: complie bindings for app schema

Actual: Error:
TypeError: Cannot read property 'type' of undefined when I've found out happens in node_modules/graphql-static-binding/dist/generators/graphcool-ts.js:48:89:

var whereType = field.args.find(function (a) { return a.name === 'where'; }).type.name; 
// field.args is undefined!!!

I was trying to dig a bit deeper but I then I had too little knowledge about project itself to realize what is really going on.

My workaround was changing generator from graphcool-ts to binding-ts and it worked but I have no idea why.

Also, it took me a while to realize I needed to add prepare-bundle: src/generated/app.graphql to app.extensions to have all imports working. My intuition was to add bundle: true to prepare-binding options but it was not working.

apollo-server 2

what about apollo-server 2 to integrate instead of yoga?
i just used it for my app and it's working with upload things... there is some stuff that apollo-server 2 won't manage ?

Issue deploying to production

When I following the instructions in the wiki Im getting the following error:
Error: data should NOT have additional properties at Output.error (/Users/davidyin/.nvm/versions/node/v8.9.1/lib/node_modules/graphcool/node_modules/graphcool-cli-engine/src/Output/index.ts:164:15) at Object.<anonymous> (/Users/davidyin/.nvm/versions/node/v8.9.1/lib/node_modules/graphcool/node_modules/graphcool-cli-engine/src/ProjectDefinition/yaml.ts:43:9) at step (/Users/davidyin/.nvm/versions/node/v8.9.1/lib/node_modules/graphcool/node_modules/graphcool-cli-engine/dist/ProjectDefinition/yaml.js:32:23) at Object.next (/Users/davidyin/.nvm/versions/node/v8.9.1/lib/node_modules/graphcool/node_modules/graphcool-cli-engine/dist/ProjectDefinition/yaml.js:13:53) at fulfilled (/Users/davidyin/.nvm/versions/node/v8.9.1/lib/node_modules/graphcool/node_modules/graphcool-cli-engine/dist/ProjectDefinition/yaml.js:4:58) at <anonymous> Exiting with code: 1
My graphcool version is: graphcool/0.9.2 (darwin-x64) node-v8.9.1

Help setting up

i wanna setup and try to deploy the app in Prisma service, so i ran yarn prisma deploy

i uncomment the endpoint part for now in prisma.yml and the prisma deploy setup console is displayed and i just pressed Enter to proceed.
at the end of the script, i encountered this error:

Hooks:
Importing seed dataset from `seed.graphql` !

ERROR: Project not found: 'prisma@dev'

{
  "errors": [
    {
      "message": "Project not found: 'prisma@dev'",
      "code": 3016,
      "requestId": "eu1:api:cjicw3a4w5ljn0a96id322smc"
    }
  ],
  "status": 200
}

Get in touch if you need help: https://www.prisma.io/forum/
To get more detailed output, run $ export DEBUG="*"
✨  Done in 74.27s.

hope someone can help me here.
thanks :)

running project with js error

I've stripped out the ts and replaced with js but cant get index.js to read them i think.

After running prisma deploy and then yarn dev i'm getting the following error:

[nodemon] starting `node -r dotenv/config src/index.js`
/Users/prisc_000/code/BHYV/airbnb-server/node_modules/graphql-yoga/node_modules/graphql-tools/dist/schemaGenerator.js:311
        Object.keys(resolveFunctions[typeName]).forEach(function (fieldName) {
               ^

TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at /Users/prisc_000/code/BHYV/airbnb-server/node_modules/graphql-yoga/node_modules/graphql-tools/dist/schemaGenerator.js:311:16
    at Array.forEach (<anonymous>)
    at addResolveFunctionsToSchema (/Users/prisc_000/code/BHYV/airbnb-server/node_modules/graphql-yoga/node_modules/graphql-tools/dist/schemaGenerator.js:303:35)
    at _generateSchema (/Users/prisc_000/code/BHYV/airbnb-server/node_modules/graphql-yoga/node_modules/graphql-tools/dist/schemaGenerator.js:90:5)
    at Object.makeExecutableSchema (/Users/prisc_000/code/BHYV/airbnb-server/node_modules/graphql-yoga/node_modules/graphql-tools/dist/schemaGenerator.js:102:20)
    at new GraphQLServer (/Users/prisc_000/code/BHYV/airbnb-server/node_modules/graphql-yoga/dist/src/index.js:89:53)
    at Object.<anonymous> (/Users/prisc_000/code/BHYV/airbnb-server/src/index.js:5:16)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
[nodemon] app crashed - waiting for file changes before starting...

This is index.js. Error is on const server on line 5.

const { GraphQLServer } = require('graphql-yoga')
const { Prisma } = require('./generated/prisma')
const { resolvers, fragmentReplacements } = require('./resolvers')

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context: req => ({
    ...req,
    db: new Prisma({
      // typeDefs: 'src/generated/prisma.graphql',
      fragmentReplacements,
      endpoint: process.env.PRISMA_ENDPOINT,
      secret: process.env.PRISMA_SECRET,
      debug: true,
    }),
  }),
})

server.start(({ port }) =>
  console.log(`Server is running on http://localhost:${port}`),
)

Any idea on what is going on here?

graphqlconfig.yml

projects:
  app:
    schemaPath: src/schema.graphql
    includes:
      - 'queries/{booking,queries}.graphql'
    extensions:
      endpoints:
        default: 'http://localhost:4000'
  prisma:
    schemaPath: "src/generated/prisma.graphql"
    includes: ["database/seed.graphql"]
    extensions:
      prisma: database/prisma.yml
      prepare-binding:
        output: src/generated/prisma.js
        generator: prisma-js

Hosted demo doesn't work

curl 'https://airbnb.now.sh/' -H 'Origin: https://airbnb.now.sh' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: */*' -H 'Connection: keep-alive' -H 'DNT: 1' --data-binary '{"query":"query {\n  topHomes {\n    id\n  }\n}","variables":"{}"}' --compressed

results in

{
  "data": null,
  "errors": [
    {
      "message": "Response not successful: Received status code 500",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "topHomes"
      ]
    }
  ]
}

How can I deploy in production with graph.cool ?

I wonder how can I deploy this sample on graph.cool

I try this
cd database
graphcool deploy

but I ended with this error

▸ [WARNING] in /Users/parweb/Sites/ww/backend/database/graphcool.yml: A valid environment variable to satisfy the declaration 'env:GRAPHCOOL_STAGE' could not be found.

▸ [WARNING] in /Users/parweb/Sites/ww/backend/database/graphcool.yml: A valid environment variable to satisfy the declaration 'env:GRAPHCOOL_CLUSTER' could not be found.

▸ [WARNING] in /Users/parweb/Sites/ww/backend/database/graphcool.yml: A valid environment variable to satisfy the declaration 'env:GRAPHCOOL_SECRET' could not be found.

▸ Invalid graphcool.yml file
▸ graphcool.yml should have required property 'stage'. missingProperty: stage

Where Can i found the proper ENV configuration on graph.cool ?

Update example to graphcool@beta

Looks like example is not updated to graphcool@beta yet.

When I follow the instructions from the README:

cd database
graphcool deploy

I get this error:

"Please either provide a secret in your graphcool.yml or disableAuth: true"

image

If I add disableAuth: true to graphcool.yml and run graphcool deploy, I receive another error:

Error: No service with name 'airbnb' and stage 'dev' found: {"response":{"data":{"deploy":null},"errors":[{"locations":[{"line":2,"column":9}],"path":["deploy"],"code":4000,"message":"No service with na
me 'airbnb' and stage 'dev' found","requestId":"deploy:system:cjbapbx1i01jx01145op7f77t"}],"status":200}

single quotes around commands don't work on Windows

This works on Windows:

    "start": "nodemon -x \"ts-node -r dotenv/config\" -e ts,graphql src/index.ts",
    "debug": "nodemon -x \"ts-node --inspect -r dotenv/config\" -e ts,graphql src/index.ts",

This doesn't:

    "start": "nodemon -x 'ts-node -r dotenv/config' -e ts,graphql src/index.ts",
    "debug": "nodemon -x 'ts-node --inspect -r dotenv/config' -e ts,graphql src/index.ts",

Use gothinkster/realworld as foundation

The purpose of this repository is to act as a reference/real-world example of how a modern Node.js-based GraphQL can be built. So far the theme of this repository was to build a (simple) Airbnb-clone.

@jlengstorf brought up the idea to adopt the gothinkster/realworld model. I like this idea and would love to collect ideas around the architecture.

Field must have a subselection

Same as prisma-labs/prisma-binding#76

query {
  homesInPriceRange(min: 0, max: 9000) {
    numRatings
  }
}
{
  "data": null,
  "errors": [
    {
      "message": "Field 'places' of type 'Place' must have a sub selection. (line 2, column 3):\n  places(where: $_where, orderBy: $_orderBy, skip: $_skip, after: $_after, before: $_before, first: $_first, last: $_last)\n  ^",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "homesInPriceRange"
      ]
    }
  ]
}

Fragments not working - missing fields in root

Expected behaviour:

Fields defined in fragments are automatically prepended to info query.

Actual behaviour:

Fields defined in fragments are not automatically prepended to info query, which causes certain resolvers to return wrong data.

Recreation:

query {
  homesInPriceRange(min: 0, max: 9000) {
    name
    numRatings
  }
}
  • numRatings is always zero, because id is undefined.
  numRatings: {
    fragment: `fragment NumRatings on Place { id }`,
    resolve: async (parent, args, ctx: Context, info) => {
      console.log(parent);
      
      const reviews = await ctx.db.query.reviewsConnection(
        { where: { place: { id: parent.id } } },
        `{ aggregate { count } }`,
      )
      return reviews.aggregate.count
    },
  },

Example of parent log:

{ name: 'Romantic, Cozy Cottage Next to Downtown' }

Cannot delete a field with relation to scalar (simple type) array.

Hi, asked this question as well in the forum, but to me this seems as a bug.

I have a type with a string array field

type Notification {
  id: ID
  params: [String!]!
}

Prisma generates the Notification_params table.

I have an issue deleting notification as I am receiving server error:

DELETE FROM "default$default"."Notification" as "Alias" WHERE TRUE
update or delete on table "Notification" violates foreign key constraint "Notification_params_nodeId_fkey" on table "Notification_params"
Now, there is no exposed function to delete something from Notification_params table
Nor, I can use Cascading delete relation.

Shouldn't these array fields be deleted automatically? Any help is greatly appreciated. If you answer here I will lint the answer in forum to this post.

Token missing in graphcool.yml

The instructions specify using the 'main' token from the graphcool service. However, it's not specified in the service definition.

Duplicated model files

The files src/schema.graphql & prisma/datamodel.graphql have duplicated information - is one of them auto-generated?

It would be a good idea to:

  • put generated files in one generated directory OR at least mention it in the first line as comment
    AND
  • add them to .gitgnore (actually src/generated is NOT .gitignore either)

Cannot return null for non-nullable field Home.avgRating

Kikstart example, start dev server, try to run queries.

This works:
2018-01-19 12 29 26

This fails:
2018-01-19 12 29 36

{
  "data": null,
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Home.avgRating.",
      "locations": [
        {
          "line": 5,
          "column": 5
        }
      ],
      "path": [
        "topHomes",
        0,
        "avgRating"
      ]
    }
  ]
}
$ prisma -v
prisma/1.0.4 (darwin-x64) node-v9.4.0

Explanation of Viewer

Hi,

I am a bit confused by Viewer in this example.

First of all, why is this necessary:
https://github.com/prismagraphql/graphql-server-example/blob/800506efcacb15c2e16bdb6d5a42ea275070a095/src/resolvers/Query.ts#L6

It seems to be doing nothing, yet if i look at schema.graphql here you have viewer in the type Query. I guess it's to match that signature, however why are we putting Viewer here in this case, next to Mutation and Query?

This example works but I'd love a little clarification on Viewer!

TypeError: Cannot convert undefined or null to object

Following the steps from the README right until yarn start leads to the following error log:

TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at /Users/marktani/projects/playground/beta-1.1/graphql-reference-server/node_modules/graphql-tools/src/schemaGenerator.ts:383:12
    at Array.forEach (<anonymous>)
    at addResolveFunctionsToSchema (/Users/marktani/projects/playground/beta-1.1/graphql-reference-server/node_modules/graphql-tools/src/schemaGenerator.ts:371:33)
    at _generateSchema (/Users/marktani/projects/playground/beta-1.1/graphql-reference-server/node_modules/graphql-tools/src/schemaGenerator.ts:85:3)
    at Object.makeExecutableSchema (/Users/marktani/projects/playground/beta-1.1/graphql-reference-server/node_modules/graphql-tools/src/schemaGenerator.ts:117:20)
    at new GraphQLServer (/Users/marktani/projects/playground/beta-1.1/graphql-reference-server/node_modules/graphql-yoga/src/index.ts:51:21)
    at Object.<anonymous> (/Users/marktani/projects/playground/beta-1.1/graphql-reference-server/src/index.ts:8:16)
    at Module._compile (module.js:573:30)
    at Module.m._compile (/Users/marktani/projects/playground/beta-1.1/graphql-reference-server/node_modules/ts-node/src/index.ts:422:23)
    at Module._extensions..js (module.js:584:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/marktani/projects/playground/beta-1.1/graphql-reference-server/node_modules/ts-node/src/index.ts:425:12)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)
[nodemon] app crashed - waiting for file changes before starting...

My graphcool version: graphcool/1.0.0-beta1.2.4 (darwin-x64) node-v8.3.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.