hewa
hewa

Reputation: 73

How to properly do a GraphQL update mutation from a nodejs function

I need to know how to do an update mutation by calling aws-amplify graphql api from my nodejs lambda,

My create mutation looks like this and it works perfectly,

const query = /* GraphQL */ `
  mutation CREATE_DRIVER($input: CreateDriverInput!) {
    createDriver(input: $input) {
      id
      name
      _version
      createdAt
      updatedAt
      _lastChangedAt
    }
  }
`;

const variables = {
    input: {
      name: 'John',
    }
  };

const options = {
    method: 'POST',
    headers: {
      'x-api-key': GRAPHQL_API_KEY
    },
    body: JSON.stringify({ query, variables })
  };

const request = new Request(GRAPHQL_ENDPOINT, options);

response = await fetch(request);
body = await response.json();
console.log(body);

And my update mutation is as follows but It doesn't work,

const query = /* GraphQL */ `
  mutation UPDATE_DRIVER($input: UpdateDriverInput!) {
    updateDriver(input: $input) {
      id
      name
      _version
      createdAt
      updatedAt
      _lastChangedAt
    }
  }
`;

const variables = {
   input: {
     id: ID
     name: 'New name',
    }
  };
    
  const options = {
    method: 'POST',
    headers: {
      'x-api-key': GRAPHQL_API_KEY
    },
    body: JSON.stringify({ query, variables })
  };
    
const request = new Request(GRAPHQL_ENDPOINT, options);

response = await fetch(request);
body = await response.json();

Given above is my update mutation code and it doesn't work. How can I fix this ?

Upvotes: 0

Views: 386

Answers (1)

hewa
hewa

Reputation: 73

My update mutation was not working It only updated the updatedAt, _lastChangedAt.
This is because I wasn't passing _version in my variables. So now my variables look like this:

const variables = {
  input: {
    id: initialObject.id
    name: 'New name',
    _version: initialObject._version
  }
};

Upvotes: 1

Related Questions