Giter Site home page Giter Site logo

graphql-js's People

Contributors

chenkie avatar christiannwamba avatar craigblunden avatar eladams avatar mairatma avatar marktani avatar nikolasburk avatar recox avatar schickling avatar thibauds 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

graphql-js's Issues

Error: Schema is not configured for mutations

I'm following the tutorial to try graphql server,
but when in this chapter https://www.howtographql.com/graphql-js/2-queries/, I get this error

input:

mutation {
  createLink(data: {
    url: "https://www.graph.cool",
    description: "A GraphQL Database"
  }) {
    id
  }
}

output:

{
  "errors": [
    {
      "message": "Schema is not configured for mutations.",
      "locations": [
        {
          "line": 1,
          "column": 1
        }
      ]
    }
  ]
}

my /src/index.js

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

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context: req => ({
    ...req,
    db: new Prisma({
      typeDefs: 'src/generated/prisma.graphql',
      endpoint: 'https://eu1.prisma.sh/public-roadleopard-58/hackernews-node/dev', // the endpoint of the Prisma DB service
      secret: 'mysecret123', // specified in database/prisma.yml
      debug: true, // log all GraphQL queryies & mutations
    }),
  }),
})

server.start(() => console.log('Server is running on http://localhost:4000'))

and I tried to find "createLink" in /generated/prisma.graphql, I got this

...
type Mutation {
  createLink(data: LinkCreateInput!): Link!
  updateLink(data: LinkUpdateInput!, where: LinkWhereUniqueInput!): Link
  deleteLink(where: LinkWhereUniqueInput!): Link
  upsertLink(where: LinkWhereUniqueInput!, create: LinkCreateInput!, update: LinkUpdateInput!): Link!
  updateManyLinks(data: LinkUpdateInput!, where: LinkWhereInput!): BatchPayload!
  deleteManyLinks(where: LinkWhereInput!): BatchPayload!
}
...

howtograpql - Nodejs + Prisma - Backend - Cannot query field 'signup' on type 'Mutation'

Good day,

I have cloned graphql-js repo, and changed relevant parts because I am using Prisma server localy.
I am using docker-compose. Here are relevan files:

package.json

{
  "name": "hackernews-node",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "node src/index.js",
    "dev": "npm-run-all --parallel start playground",
    "playground": "graphql playground",
    "prisma": "prisma",
    "graphql": "graphql"
  },
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "graphql-yoga": "^1.7.0",
    "jsonwebtoken": "^8.2.0",
    "prisma-binding": "^2.0.2"
  },
  "devDependencies": {
    "graphql-cli": "^2.16.4",
    "npm-run-all": "^4.1.2",
    "prisma": "^1.9.0"
  }
}

docker-compose.yml

version: '3'
services:
  prisma:
    image: prismagraphql/prisma:1.16
    restart: always
    ports:
    - "4466:4466"
    environment:
      PRISMA_CONFIG: |
        port: 4466
        databases:
          default:
            connector: postgres
            host: postgres
            port: 5432
            user: prisma
            password: prisma
            migrations: true
  postgres:
    image: postgres:10.5
    restart: always
    ports:
    - "5432:5432"
    environment:
      POSTGRES_USER: prisma
      POSTGRES_PASSWORD: prisma
    volumes:
      - postgres:/var/lib/postgresql/data
volumes:
  postgres:

.graphqlconfig.yml

projects:
  app:
    schemaPath: src/schema.graphql
    extensions:
      endpoints:
        default: http://localhost:4466
  database:
    schemaPath: src/generated/prisma.graphql
    extensions:
      prisma: database/prisma.yml

prisma.yml

endpoint: http://localhost:4466
datamodel: datamodel.graphql
secret: mysecret123
hooks:
  post-deploy:
    - yarn graphql get-schema --project database

.src/index.js

const { GraphQLServer } = require('graphql-yoga')
const { Prisma } = require('prisma-binding')
const Query = require('./resolvers/Query')
const Mutation = require('./resolvers/Mutation')
const AuthPayload = require('./resolvers/AuthPayload')
const Subscription = require('./resolvers/Subscription')
const Feed = require('./resolvers/Feed')

const resolvers = {
  Query,
  Mutation,
  AuthPayload,
  Subscription,
  Feed
}

const server = new GraphQLServer({
  typeDefs: './src/schema.graphql',
  resolvers,
  context: req => ({
    ...req,
    db: new Prisma({
      typeDefs: 'src/generated/prisma.graphql',
      endpoint: 'http://localhost:4466',
      secret: 'mysecret123',
      debug: true,
    }),
  }),
})
server.start(() => console.log(`Server is running on http://localhost:4466`))

When I run yarn dev, server starts, playground opens, everythinf works , but there are no signup, login, post mutations.

Bellow is image of mutations from GraphQL Playground.

screenshot 2018-09-22 12 03 37

When trying to write post mutation I get:

mutation {
  signup(
    name: "Alice"
    email: "[email protected]"
    password: "graphql"
  ) {
    token
    user {
      id
    }
  }
}

Cannot query field 'signup' on type 'Mutation'

Websocket for subscriptions won't connect

Whenever I try to create a subscription for Link and then perform a createLink mutation. Nothing happens in the subscription tab when I expect to see a subscription to be logged. When I opened the console I noticed this.

WebSocket connection to 'ws://locahost:3000/subscriptions' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED

and it will continuously attempt to reconnect and fail every time.

Here is a link to my repo if anyone could help me https://github.com/charlieroth/howtogql-node. I followed the tutorial step for step and went back through multiple times and checked my code and couldn't find anything wrong.

Suggestion: Please include all CRUD operations

First off, great tutorial and very helpful. Somewhere near the end of chapter 3 or 4 you pose a challenge the write the rest of the CRUD operations for the Link type:

 type Query {
  # Fetch a single link by its `id`
  link(id: ID!): Link
}

type Mutation {
  # Update a link
  updateLink(id: ID!, url: String, description: String): Link

  # Delete a link
  deleteLink(id: ID!): Link
}

I thought that was a great challenge, and I went ahead and did it. However, that challenge was given before the Prisma integration, which involved refactoring all of the resolvers. That broke the challenge mutations, and they were never revisited again, even in the GitHub repo for the finished project. I really wish you had revisited those other mutations after the Prisma integration to round out all of the operations.

I went ahead and implemented them myself using the Prisma docs and Google, and there was some great non-trivial stuff to solve in there, especially around deleting and how to handle cascade deletes.

I understand that going into all of that is more relevant to Prisma than GraphQL; But I think that if you're going to bring in Prisma as a core part of the tutorial, you should cover all the operations. It would make the final project feel more complete. Plus, going back to solve an earlier challenge with new tools makes for a more compelling tutorial.

Just my $0.02

prisma deploy did not work

when I followed code on the tutorial, and run prisma deploy
the console shows

Cluster undefined does not exist.

Is this about the prisma version ?
I use prisma 1.8.3, while the tutorial is prisma 1.6

Tutorial 6-authentication - singup:null, no error

I am following the tutorial and i just encountered a problem on the signup step:

Auswahl_003

There is no error (neither in the server console, nor in the API response). I don't know where the problem is.

The signup resolver is not beeing invoked (i have added a console.log('Test') on the top of the function to check this).

My package.json:

{
  "name": "hackernews-node",
  "version": "1.0.0",
  "main": "src/index.js",
  "license": "MIT",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "graphql-yoga": "^1.17.4",
    "jsonwebtoken": "^8.5.1",
    "prisma-client-lib": "^1.33.0"
  }
}

Prisma setup instructions might be outdated

I have followed the instructions in the README.md file:

  1. Deploy the Prisma database service
    yarn prisma deploy
    When prompted where (i.e. to which cluster) you want to deploy your service, choose any of the public clusters, e.g. public-us1 or public-eu1. (If you have Docker installed, you can also deploy locally.)

Actually it does not prompt for any cluster, it returns:

myfolder\graphql-js> yarn prisma deploy
yarn run v1.6.0
$ prisma deploy
 !    Cluster undefined does not exist.

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

I have never used Prisma or GraphQL before, is there something I'm missing?
I'm at this step of the tutorial: https://www.howtographql.com/graphql-js/4-adding-a-database/
Everything worked out perfectly until now.

EDIT:

Running "prisma init" seems to be giving me the right output:

myfolder\graphql-js>prisma init
? Connect to your database, set up a new one or use hosted sandbox? (Use arrow keys
)

  You can set up Prisma  for local development (requires Docker)
> Use existing database      Connect to existing database
  Create new database        Set up a local database using Docker

  Or use a free hosted Prisma sandbox (includes database)
  sandbox-eu1                Free development server on Prisma Cloud (incl. databas
e)
(Move up and down to reveal more choices)

I select "sandbox-eu1":

\graphql-js>prisma init
? Connect to your database, set up a new one or use hosted sandbox? sandbox-eu1
            Free development server on Prisma Cloud (incl. database)
? How do you want to call your service? graphql-js
? To which stage do you want to deploy? dev
Created 2 new files:                                                               

  prisma.yml           Prisma service definition
  datamodel.graphql    GraphQL SDL-based datamodel (foundation for database)


You now can run $ prisma deploy to deploy your database service.
'docker-compose' is not recognized as an internal or external command,
operable program or batch file.

To install docker-compose, please follow this link: https://docs.docker.com/compose/install/

As suggested by the cmd output, I run "prisma deploy":

\graphql-js>prisma deploy
Creating stage dev for service graphql-js โˆš
Deploying service `graphql-js` to stage `dev` to server `prisma-eu1` 197ms

Changes:

  User (Type)
  + Created type `User`
  + Created field `id` of type `GraphQLID!`
  + Created field `name` of type `String!`
  + Created field `updatedAt` of type `DateTime!`
  + Created field `createdAt` of type `DateTime!`

Applying changes 1.3s

Your Prisma GraphQL database endpoint is live:

  HTTP:  https://eu1.prisma.sh/myrandomstring/graphql-js/dev
  WS:    wss://eu1.prisma.sh/myrandomstring/graphql-js/dev

Now I can proceed to step 3 and 4:

  1. Set the Prisma service endpoint
    From the output of the previous command, copy the HTTP endpoint and paste it into src/index.js where it's used to instantiate the Prisma binding. You need to replace the current placeholder PRISMA_ENDPOINT:
  2. Start the server & open Playground
    To interact with the API in a GraphQL Playground, all you need to do is execute the dev script defined in package.json:

However if I now go to http://localhost:4000/ and try to run any query I get this:

{
  "data": null,
  "errors": [
    {
      "message": "Not authenticated",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "post"
      ]
    }
  ]
}

Based on my understanding this is happening because I'm missing the authorization header, first I need to generate a token:

\graphql-js>prisma token
There is no secret set in the prisma.yml

Damn, there's no secret ๐Ÿ˜ž Ok, let's add it: (I will copy the same secret from src\index.js)

endpoint: https://eu1.prisma.sh/myrandomstring/graphql-js/dev
datamodel: datamodel.graphql
secret: "mysecret123"

Ok, now it seems to work:

\graphql-js>prisma token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InNlcnZpY2UiOiJncmFwaHFsLWpzQGRldiIsInJvbGVzIjpbImFkbWluIl19LCJpYXQiOjE1MjQ2NjM2NDYsImV4cCI6MTUyNTI2ODQ0Nn0.sBx6zl-xv30Cw03UutMssjA7i272gXkuJUHmHNlaeBI

Let's add it to the HTTP headers in the GraphQL playground: (as shown in https://www.howtographql.com/graphql-js/4-adding-a-database/)

{
  "Authentication": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InNlcnZpY2UiOiJncmFwaHFsLWpzQGRldiIsInJvbGVzIjpbImFkbWluIl19LCJpYXQiOjE1MjQ2NjM2NDYsImV4cCI6MTUyNTI2ODQ0Nn0.sBx6zl-xv30Cw03UutMssjA7i272gXkuJUHmHNlaeBI"
}

Restart everything up, go to localhost:4000, run a test query:

{
  "data": null,
  "errors": [
    {
      "message": "Not authenticated",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "post"
      ]
    }
  ]
}

Still not working! ๐Ÿ’ฉ

subscription with react js don't know how to use subscription with react js to make like in lyrics and update in other screens

const graphql = require('graphql');
const { GraphQLObjectType, GraphQLList, GraphQLNonNull, GraphQLID } = graphql;
const mongoose = require('mongoose');
const Lyric = mongoose.model('lyric');
const LyricType = require('./lyric_type');

const { PubSub, withFilter } = require('graphql-subscriptions');

const pubsub = new PubSub();

const SubscriptionQuery = new GraphQLObjectType({
name: 'Subscription',
fields: {
addLike: {
type: LyricType,
args: { id: { type: GraphQLID } },
resolve(parentValue, { id }) {
const AddLike = Lyric.like(id);
if (!AddLike) throw new Error('lyric does not exist');
pubsub.publish('LikeAdded', { LikeAdded: addLike, id: AddLike.id });
return AddLike;
},
LikeAdded: {
subscribe: withFilter(
() => pubsub.asyncIterator('LikeAdded'),
(payload, variables) => {
const ly = Lyric.findById(variables.id);
return ly;
}
),
},
},
},
});

module.exports = SubscriptionQuery;

jwt verify return different data result in jsonwebtoken^8.3.0

jwt.verify() return below data object,
{ data: { userId: 'cjjy7z3h0e2iq0b29sz5m46zj' }, iat: 1532347227 } in "jsonwebtoken": "^8.3.0"
suggest change from

function getUserId(context) {
  const Authorization = context.request.get('Authorization')
  if (Authorization) {
    const token = Authorization.replace('Bearer ', '')
    const { userId } = jwt.verify(token, APP_SECRET)
    return userId
  }

  throw new Error('Not authenticated')
}

to

function getUserId(context) {
    const Authorization = context.request.get('Authorization');

    if(Authorization) {
        const token = Authorization.replace('Bearer ', '');
        const result = jwt.verify(token, APP_SECRET); 
        const {userId} = result.data;
        return userId;
    }

    throw new Error('Not authenticated')
}

Cannot read property 'hash' of undefined

I'm trying to test signup using the playground When I read the Authentication, After I followed the tutorial step by step. but I got an Cannot read property 'hash' of undefined error
Here are the screenshots:
image

May be checkout new branch every chapter for example is better

parser: "babylon" is deprecate

After command prisma generate i see

Generating schema... 32ms
{ parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }.

How to fix it?

TypeError: Cannot read property 'publicClusters' of undefined

Good afternoon,

I have cloned the repository, and have installed and run dependancies as instructed, however I am getting the following error. Do you know what may be causing this?

TypeError: Cannot read property 'publicClusters' of undefined
at Environment. (/Users/Charles/Sites/tutorials/graphql-js/node_modules/graphcool-yml/dist/Environment.js:103:39)
at step (/Users/Charles/Sites/tutorials/graphql-js/node_modules/graphcool-yml/dist/Environment.js:40:23)
at Object.next (/Users/Charles/Sites/tutorials/graphql-js/node_modules/graphcool-yml/dist/Environment.js:21:53)
at fulfilled (/Users/Charles/Sites/tutorials/graphql-js/node_modules/graphcool-yml/dist/Environment.js:12:58)
at
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:38543) UnhandledPromiseRejectionWarning: Error: No cluster set. Please set the "cluster" property in your graphcool.yml
at /Users/Charles/Sites/tutorials/graphql-js/node_modules/graphql-config-extension-graphcool/dist/index.js:137:31
at step (/Users/Charles/Sites/tutorials/graphql-js/node_modules/graphql-config-extension-graphcool/dist/index.js:40:23)
at Object.next (/Users/Charles/Sites/tutorials/graphql-js/node_modules/graphql-config-extension-graphcool/dist/index.js:21:53)
at fulfilled (/Users/Charles/Sites/tutorials/graphql-js/node_modules/graphql-config-extension-graphcool/dist/index.js:12:58)
at
(node:38543) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Subscriptions not showing new additions to the database

I went through the tutorial and am able to perform queries and mutations on it but when I run subscription in the playground it doesn't output new anything when I add new links to the database. I removed the where filter and it still doesn't work. Considering everything else works this seems to be an issue with the tutorial.

Subscription error with the latest version of prisma-binding package

When I upgrade prisma-binding from ^2.0.2 to ^2.1.4

newLink (and newVote) subscriptions fail with

{
  "error": {
    "name": "TypeError",
    "message": "Cannot read property 'link' of undefined"
  }
}

This error happens when I follow the tutorial today. It is not an issue with the repository itself, but with the related tutorial which seems to not reflect some recent breaking changes between minor versions of prisma-binding

reproduce

  1. install this repository, yarn dev, go to playground, sign up, provide authorization header
  2. test that newLink subscription works
  3. yarn add graphql-yoga@latest
    yarn add prisma-binding@latest
  4. restart with yarn dev
  5. test newLink subscription again and observe the error

Update README: add info about starting MongoDB.

After following README instruction I get an error:

(node:19472) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: failed to connect toserver [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
(node:19472) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections thatare not handled will terminate the Node.js process with a non-zero exit code.

Would be nice to add info about starting DB service prior to running the server

Could not connect to websocket endpoint ws://localhost:4000/

Unable to complete the subscriptions tutorial here https://www.howtographql.com/graphql-js/7-subscriptions/ due to this issue getting following error:

{
  "error": "Could not connect to websocket endpoint ws://localhost:4000/. Please check if the endpoint url is correct."
}

The schema that I'm sending in request is here:

subscription {
  newLink {
    node {
      id
      url
      description
      postedBy {
        id
        name
        email
      }
    }
  }
}

Here is the link to my repo: https://github.com/mrimran/hackernews

The above error is coming in Firefox whereas when I tried it on Chrome I'm facing the below issue which is already reported

#42

Error: No `typeDefs` provided when calling `new Prisma()`

I'm doing the node.js howtographql.com tutorial and am at the Connecting Server and Database with Prisma Bindings section where we are hooking up the playground to work on both the GraphQL and Prisma API. Playground and the schema load fine for the Prisma database but I'm getting a

Error: NotypeDefsprovided when callingnew Prisma()``

when I try to access the application side. When I viewed the network tab on chrome, The response has Invalid options provided to ApolloServer: No typeDefsprovided when callingnew Prisma()``.

On the playground I see a

{ "error": "Unexpected token < in JSON at position 0" }

Below is the section that it complains about on my index.js file:

const server = new GraphQLServer({
      typeDefs: './schema.graphql',
      resolvers,
      context: req => ({
                ...req,
               db: new Prisma({
                        typeDefs: 'src/generated/schema.graphql',
                        endpoint: 'https://eu1.prisma.sh/public-alabasterdancer-573/project-barca/dev',
                        secret: 'mysecret123',
                        debug: true
                })
        })
})

The only thing different here than the tutorial is the typeDef: './schema.graphql, line (second line) because when I put the ./src/ in front of it, I get this error while launching the server Error: No schema found for path: /home/graphql/dev/server/src/src/schema.graphql. Which led me to believe that the ./src is not needed. I also tried without the ./ and almost about every combo possible on both typeDefs in that section.

I've looked through everything I know but being very new at this, I may have missed something glaring. I was wondering if this is something that others have seen? Is it just the way I've written the path? The path strings not being parsed properly? Also why is it complaining about typeDef on the 'new Prisma()' invocation when the database side works fine. I don't think I fully understand the inner workings quite enough to see the connection. Any help is appreciated and apologies in advance if this is something stupid that I've missed. Thanks.

Confusion at the end of 'Applying Authentication' chapter.

I have been following along the graphql-js tutorial, and when I got to the end of 'Applying authentication' chapter, I hit a snag:

I got to the code example for the 'vote' mutation, and when finished, the tutorial explains what is happening. It then goes on to instruct the user to restart the server and send a 'vote' mutation in the app playground. This didn't work for me. I spent quite some time, and actually had to leave and come back (to clear my head) a total of 3 times.

screen shot 2018-03-23 at 12 15 53 p
m

I am embarrassed to even write this, having been a 'professional' JS developer for almost 2 years now, but I never exported 'vote'. There is no hint or reminder, and it is not shown in the code. I ended up coming to this github and comparing the source code to mine, which is how I found the discrepancy.

As someone who 'knows' their JS, I consider this user error on my part, but I can certainly see this affecting greener devs, especially since I know I was so concerned with understanding the graphql part that I overlooked something as 'basic' as exporting my methods.

Anyway, just wanted to point that out, and would also like to offer up that I would be happy to submit a PR myself if this is deemed an actual bug.

Thanks for the hard work and overall great tutorials!

requestAnimationFrame eating up CPU

Just wanted to let you know there's an animation or something in your tutorial (which is excellent btw!) that's causing my CPU to kick into overdrive. Opening the dev console and adding window.requestAnimationFrame = () => {} seems to fix the issue.

Cannot GET /graphiql

I follow the tutorial until reaching to authentication lesson but in middle of it when we make Authenticating requests and Linking User to created links and run the server , It run correctly but when i go my browser
by the endpoint url "http://localhost:3000/graphiql" , I get this error

Cannot GET /graphiql

screenshot from 2017-11-19 19-33-35

Authentication: Cannot find 'bcryptjs'

ERROR:Cannot find module bcryptjs.
I got this error while doing node src/index.js at end of the Authentication section.

module.js:549
    throw err;
    ^
Error: Cannot find module 'bcryptjs'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/aby/Developer/Projects/React/GraphQL/hackernews-node/src/resolvers/Mutation.js:1:78)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

I deleted node_modules folder and reinstalled all via npm install. Still bcryptjs is missing.
My package.json shows

"dependencies": {
    "bcrypt": "^3.0.0",
    "graphql-yoga": "^1.16.2",
    "jsonwebtoken": "^8.3.0",
    "prisma-binding": "^2.1.5"
  }

Unable to signup, invalid token, unable to authenticate

I'm trying to signup using the playground, but I'm unable to do it because I get an "invalid token error".

Here are the steps to reproduce:

git clone https://github.com/howtographql/graphql-js
cd graphql-js
yarn install
cd database
vim prisma.yml
# comment the first line (endpoint:...)
cd ..
prisma deploy
# > Demo server
# > prisma-eu1
# > database
# > dev

# endpoint is now set in the file database/prisma.yml
# copy this value, and replace the endpoint value in src/index.js

prisma token
# copy this value as the Bearer token for the Authorization Header
yarn dev

Then when I execute the following query in the playground on the database/dev with the previously generated token

{ links { id } }

It's working as expected.

Nevertheless when selecting the app/default project in the playground and executing the following query

mutation {
  signup(
    name: "myName"
    email: "[email protected]"
    password: "mystrongpassword"
  ) {
    token
    user {
      id
    }
  }
}

I got the following error

{
  "data": {
    "signup": null
  },
  "errors": [
    {
      "message": "Your token is invalid. It might have expired or you might be using a token from a different project.",
      "locations": [],
      "path": [
        "createUser"
      ],
      "code": 3015,
      "requestId": "eu1:api:cjjckt..."
    }
  ]
}

I tried with and without the previoulsy generated token and got the same error.

I'm confused. As far as I understand, the prisma layer needs a token to execute the signup mutation, it makes sense otherwise the prisma layer would be open to anyone and we only want our app (or authenticated users) to be able to execute query on our prisma layer. Nevertheless I don't see anything in this repo, in the application layer that would authenticate to the prisma layer.
After logging in I could use the token from the user and pass it to the prisma layer but for the signup I don't have any token.
Am I missing something? Is it left to the developer because it is specific to the way we want our application layer to communicate with our prisma layer?

prisma version:
prisma/1.11.0 (linux-x64) node-v10.4.0

Named Pipes Issue

I am trying to follow the backend tutorial for graphql.js on the how to graphql website. I am running the following:

  • Windows 7, 64 bit
  • Node.js version 8.9.4
  • Docker Toolbox 18.0.2-ce

When I run graphql create hackernews-node --boilerplate node-basic, it asks for the location of where I want to deploy. I select local to create a local cluster and it says I need Docker installed.

After making the selection, I get an error:

[graphql create] Running boilerplate install script...
Running $ prisma deploy...

? Please choose the cluster you want to deploy "hackernews-node@dev" to

local           Local cluster (requires Docker)
Booting local development cluster !
 !    Windows named pipe error: The system cannot find the file specified.
 !    (code: 2)
 !

Get in touch if you need help: https://www.graph.cool/forum
To get more detailed output, run $ export DEBUG="*"
 !    No cluster set. Please set the "cluster" property in your prisma.yml

Get in touch if you need help: https://www.graph.cool/forum
To get more detailed output, run $ export DEBUG="*"
events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: spawn prisma ENOENT
    at notFoundError (D:\graphQL\yoga\hackernews-node\.install\node_modules\cros
s-spawn\lib\enoent.js:11:11)
    at verifyENOENT (D:\graphQL\yoga\hackernews-node\.install\node_modules\cross
-spawn\lib\enoent.js:46:16)
    at ChildProcess.cp.emit (D:\graphQL\yoga\hackernews-node\.install\node_modul
es\cross-spawn\lib\enoent.js:33:19)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)

Once I set the DEBUG flag, I get this:

Booting local development cluster... !
Error: Windows named pipe error: The system cannot find the file specified. (cod
e: 2)

    at Output.<anonymous> (D:\graphQL\apollo\hackernews-node\node_modules\prisma
-cli-engine\src\Output\index.ts:166:15)
    at step (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-engine\di
st\Output\index.js:40:23)
    at Object.next (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-en
gine\dist\Output\index.js:21:53)
    at D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-engine\dist\Out
put\index.js:15:71
    at new Promise (<anonymous>)
    at __awaiter (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-engi
ne\dist\Output\index.js:11:12)
    at Output.error (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-e
ngine\dist\Output\index.js:205:16)
    at Function.<anonymous> (D:\graphQL\apollo\hackernews-node\node_modules\pris
ma-cli-engine\src\Command.ts:75:15)
    at step (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-engine\di
st\Command.js:32:23)
    at Object.throw (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-e
ngine\dist\Command.js:13:53)
    at rejected (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-engin
e\dist\Command.js:5:65)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)
Error: No cluster set. Please set the "cluster" property in your prisma.yml
    at Deploy.<anonymous> (D:\graphQL\apollo\hackernews-node\node_modules\prisma
-cli-core\src\commands\deploy\index.ts:148:13)
    at step (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-core\dist
\commands\deploy\index.js:42:23)
    at Object.next (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-co
re\dist\commands\deploy\index.js:23:53)
    at fulfilled (D:\graphQL\apollo\hackernews-node\node_modules\prisma-cli-core
\dist\commands\deploy\index.js:14:58)
    at <anonymous>
Exiting with code: 1
events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: spawn prisma ENOENT
    at notFoundError (D:\graphQL\apollo\hackernews-node\.install\node_modules\cr
oss-spawn\lib\enoent.js:11:11)
    at verifyENOENT (D:\graphQL\apollo\hackernews-node\.install\node_modules\cro
ss-spawn\lib\enoent.js:46:16)
    at ChildProcess.cp.emit (D:\graphQL\apollo\hackernews-node\.install\node_mod
ules\cross-spawn\lib\enoent.js:33:19)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)

I can't find any reference to this error, or how to fix it. Any help would be greatly appreciated!

Defining secret for prisma-binding

I'm new to Prisma and graph QL so apologies if this comes down to lack of knowledge.

According to the guide, the secret isn't defined when you initiate db within the context of the GraphQL Server.

https://www.howtographql.com/graphql-js/5-connecting-server-and-database/

I've been getting authentication errors on my application requests within the playground for hours until I looked through the actual package to find out its a required field:

https://github.com/prismagraphql/prisma-binding

Statically defining the secret resolved the issue.

PR #35

I have problem with es6 syntax

When i try to run yarn dev I always have this issue

graphql-js/src/index.js:19
    ...req,
    ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

Im running node v6.11.3

I think this might be relate to es6 syntax for rest operator

createdAt not included in schema.graphql

Hey,

Thanks for the great tutorial, it was very helpful in learning GraphQL. I actually started the React tutorial first, then decided to come and do this one, as the React one uses this same backend. I thought it would be a much better learning experience to build the backend tutorial first, then use that backend code to build the frontend tutorial. However, I hit a stumbling block immediately upon trying to use my backend code:

In this tutorial, the Link { createdAt } field is only used in the Prisma schema, not in the main API schema. If you download the server starter code listed in the React tutorial, it is is correctly listed in both schemas.

Further, the createdAt type is DateTime, which doesn't seem to be a standard GraphQL type. Using it requires that you declare "scalar DateTime" at the top of your API schema (as seen in the React tut starter). Doing that worked for me with no additional dependencies, but I have no idea why.

Some more clarity on that within the tutorial would be helpful.

Improving the feed query

First of all, thanks for the great course. As someone with zero experience in GraphQL, the course helped me get a deeper understanding of how things work.

I feel like the feed query, defined here https://github.com/howtographql/graphql-js/blob/master/src/resolvers/Query.js#L1 , can be improved upon. Currently, the server makes a database request for both links and count, regardless of whether the client only asked for one or the other.

Modifying the code a bit, by rewriting the separate database calls into functions, seems to have fixed the issue.

const feed = (root, args, context, info) => {
  const createWhereClause = () =>
    args.filter
      ? {
          OR: [
            { description_contains: args.filter },
            { url_contains: args.filter }
          ]
        }
      : {};

  const links = () =>
    context.prisma.links({
      where: createWhereClause(),
      skip: args.skip,
      first: args.first,
      orderBy: args.orderBy
    });

  const count = () =>
    context.prisma
      .linksConnection({
        where: createWhereClause()
      })
      .aggregate()
      .count();

  return {
    links,
    count
  };
};

module.exports = {
  feed
};

I am not sure if this is the best approach to the problem, however this has reduced the redundant database calls.

Subscriptions not showing after mutation

I know this issue has been raised before in #14 but I feel this must be a different problem as the previous issue is over a year old and appears to have been resolved.

I have followed the tutorial exactly and everything works except the subscriptions. They sit there saying 'Listening...' but never show data.

This is the vote subscription

function newVoteSubscribe (parent, args, context, info) {
  return context.prisma.$subscribe.vote({ mutation_in: ['CREATED'] }).node()
}

const newVote = {
  subscribe: newVoteSubscribe,
  resolve: payload => {
    return payload
  }
}

which appears to be as it should compared to the repo on here and I don't get an error, simply no response in playground. I've tried adding where: { mutation_in... and an empty object in vote() but it makes no difference. The newLinkSubscribe is the same.

Unable to create post, Invalid token

Hey there,

I'm following the tutorial from howtographql
I was able to signup a new user thanks to this issue #34

Now i'm signing up the user with this mutation

mutation {
  signup(
    email: "[email protected]"
    name: "test test"
    password: "123123"
  )
  {
    token
    user {
      id
    }
  }
}

Then i copy the token in the header tab :

{
  "Authorization" : "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjampjd3ZpODFwNGFoMGI4Mnp5dGtxb3FtIiwiaWF0IjoxNTMxMDU4ODgyfQ.WYiy_T-UnmLhlzST3QDbyZABaQwlgcKqh7pYDlnut7g"
} 

And try this mutation :

mutation {
  post(
    url: "www.graphql-europe.org"
    description: "Europe's biggest GraphQL conference"
  ) {
    id
  }
}

To receive this error :

{
  "data": null,
  "errors": [
    {
      "message": "invalid token",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "post"
      ]
    }
  ]
}

I don't get why i'm stuck with this, do you have any hints ?
Thanks in advance

Idea for dynamic models with validation

ex:
user.json
{
peroperties:{
"_id":{ "type": ID, "unique": true},
"firstName":{ "type": String},
"lastName":{ "type": String},
"email":{ "type": String, "unique": true, "index": true},
}
}

something like that

ERROR -> "Cannot read property 'get' of undefined" when using post with auth headers

Hello all,

Any ideas why I'm getting this error?

My utils file here: https://github.com/mmswi/graphQL-tut/blob/master/src/utils.js
My mutation here: https://github.com/mmswi/graphQL-tut/blob/master/src/resolvers/Mutation.js
Note, I've hardcoded the user id and used a try catch block, as I got an error in the console that was saying:
(node:16656) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Anyways, same "Cannot read property 'get' of undefined" error received when not using a try catch block.

With the hardcoded id, the post function works, so I'm wondering why is the context get returning that error. The auth headers have been added also in the graphql playground
{ "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJjamd5ODg1MXczZGd3MGIwOG91dHE1OWRrIiwiaWF0IjoxNTI1ODkyMjQwfQ.mW-uDhlG3cGJRi14lw2g_YQSVLWS1Xnkw_VzK_QliO0" }

Thanks

Add Context for Subscriptions

When you try to create a nested query in the Link subscription, the response is [Object object]. I opened an issue at apollographql/subscriptions-transport-ws#306, and we found out that this issue occures because mongo and the dataloaders are missing from the subscription context.

subscription {
  Link(filter:{
    mutation_in: [CREATED]
  }) {
    mutation
    node {
      id
      url
      description
      postedBy {
          name
      }
    }
  }
}

The solution:

    SubscriptionServer.create(
            {
               execute, 
               subscribe, 
               schema,
               onOperation: (message, params, webSocket) => 
                   Object.assign(
                      params, 
                      {
                          context: {
                              mongo, 
                              dataloaders: buildDataloaders(mongo)
                          }
                      })
            },
            { server, path: '/subscriptions' },
      );

When I use string file path for typeDefs,there is a error: Cannot parse the unexpected character "/".

When I use string file path for typeDefs,there is a error: Cannot parse the unexpected character "/".

const server = new GraphQLServer({
    typeDefs: './src/schema.graphql',
    resolvers,
})

/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/language/lexer.js:302
throw (0, _error.syntaxError)(source, pos, unexpectedCharacterMessage(code));
^
GraphQLError: Syntax Error: Cannot parse the unexpected character "/".
at syntaxError (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/error/syntaxError.js:24:10)
at readToken (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/language/lexer.js:302:32)
at Object.lookahead (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/language/lexer.js:61:43)
at Object.advanceLexer [as advance] (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/language/lexer.js:52:33)
at expect (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/language/parser.js:1296:11)
at parseDocument (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/language/parser.js:107:3)
at Object.parse (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql/language/parser.js:38:10)
at getDocumentFromSDL (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql-import/dist/index.js:107:26)
at Object.importSchema (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql-import/dist/index.js:59:20)
at mergeTypeDefs (/Users/harry/reactworkspace/graphql-yoga-server/hackernews-node/node_modules/graphql-yoga/dist/index.js:402:37)

"root" and "parent" used interchangeably with no explanation

At different times in the tutorial, the GraphQL resolver parameter "parent" is named "root", even though it is always referred to as "parent". Either making the terminology consistent or providing explanation of why it is not consistent would have helped reduce some of my confusion, as this is the first time I'm really using GraphQL.

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.