Search code examples
javascriptreact-apollographql-js

Apollo GraphQL Error expected " ] " found " : "


Hey I'm getting an error when I run my app. it is GraphQLError: Syntax Error: Expected "]", found ":". At the bottom of the stack trace it has path: undefined, [0] locations: [ { line: 12, column: 17 } ],

Here's my typeDefs.js

const { gql } = require("apollo-server-express");

const typeDefs = gql`
  type User {
    _id: ID
    firstName: String
    lastName: String
    email: String
  }

  type Metric {
    _id: ID
    name: String
    labels: [key: String!, value: String!]
    values: [value: Number!, timestamp: Date!]
  }

  type Auth {
    token: ID
    user: User
  }

  type Query {
    user: User
    userById(userId: ID): User
    metric(metricId: ID): Metric
    metrics: [Metric]!
  }

  type Mutation {
    addUser(
      firstName: String!
      lastName: String!
      email: String!
      password: String!
    ): Auth
    updateUser(firstName: String, lastName: String, email: String): User
    login(email: String!, password: String!): Auth
    addMetric(
      name: String!
      labels: [key: String!, value: String!]
      values: [value: Number!, timestamp: Date!]
      ): Metric
  }
`;

module.exports = typeDefs;

Here's my Model for metrics as i'm assuming it has something to do with how im setting up the arrays in graphql, maybe this will help!

const mongoose = require("mongoose");

const { Schema } = mongoose;

const metricsSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  labels: [
    {
      key: {
        type: String,
        required: true,
      },
      value: {
        type: String,
        required: true,
      },
    },
  ],
  values: [
    {
      value: {
        type: Number,
        required: true,
      },
      timestamp: {
        type: Date,
        default: Date.now,
        required: true,
      },
    },
  ],
});

const Metrics = mongoose.model("Metrics", metricsSchema);
module.exports = Metrics;

Thanks..

I tried changing how the arrays are wrote in the typeDefs and could not get past this error.


Solution

  • You can try adding new type for label and value.

    type Label {
      key: String!
      value: String!
    }
    
    type Value {
      value: Number!
      timeStamp: Date!
    }
    
    type Metric {
      _id: ID
      name: String
      labels: [Label!]
      values: [Value!]
    }
    
    // Change type of addMetric params in your mutations
    
    type Mutation {
      addMetric(
        name: String!
        labels: [Label!]
        values: [Value!]
        ): Metric
    }