0

I used the email-password template to setup my graphcool server with user authentication. I want to add a property for “name” when signing up a new user. I added name to the User model and updated the signup.graphql and signup.ts code as shown below.

I get an error when running the createUser mutation which says “name is not defined”. I’m not sure what the problem is. Any help is greatly appreciated!

signup.graphql

extend type Mutation {
  signupUser(email: String!, password: String!, name: String): SignupUserPayload
}

signup.ts

interface EventData {
  email: string
  password: string
  name: string
}

const SALT_ROUNDS = 10

export default async (event: FunctionEvent<EventData>) => {
  console.log(event)

  try {
    const graphcool = fromEvent(event)
    const api = graphcool.api('simple/v1')

    const { email, password } = event.data

    if (!validator.isEmail(email)) {
      return { error: 'Not a valid email' }
    }

    // check if user exists already
    const userExists: boolean = await getUser(api, email)
      .then(r => r.User !== null)
    if (userExists) {
      return { error: 'Email already in use' }
    }

    // create password hash
    const salt = bcrypt.genSaltSync(SALT_ROUNDS)
    const hash = await bcrypt.hash(password, salt)

    // create new user
    const userId = await createGraphcoolUser(api, email, hash, name)

    // generate node token for new User node
    const token = await graphcool.generateNodeToken(userId, 'User')

    return { data: { id: userId, token } }
  } catch (e) {
    console.log(e)
    return { error: 'An unexpected error occured during signup.' }
  }
}

async function getUser(api: GraphQLClient, email: string): Promise<{ User }> {
  const query = `
    query getUser($email: String!) {
      User(email: $email) {
        id
      }
    }
  `

  const variables = {
    email,
  }

  return api.request<{ User }>(query, variables)
}

async function createGraphcoolUser(api: GraphQLClient, email: string, password: string, name: string): Promise<string> {
  const mutation = `
    mutation createGraphcoolUser($email: String!, $password: String!, $name: String) {
      createUser(
        email: $email,
        password: $password,
        name: $name
      ) {
        id
      }
    }
  `

  const variables = {
    email,
    password: password,
    name: name
  }

  return api.request<{ createUser: User }>(mutation, variables)
    .then(r => r.createUser.id)
Jack Doyle
  • 23
  • 4

1 Answers1

0

Found the answer. I was missing name from this line here..

const { email, password } = event.data

Changing to this solved it

const { email, password, name } = event.data
Jack Doyle
  • 23
  • 4