AWS appsync example for mutation using Node.js
3 min read

AWS appsync example for mutation using Node.js

Welcome folks,

AWS AppSync is a service that allows developers to easily build apps with real-time and offline capabilities.

Read the Basics and setup from /aws-appsync-setup-using-nodejs


Schema:

input CreatePostInput {
	author: String!
	id: String!
	url: String
	content: String
	title: String
}

input DeletePostInput {
	author: String!
	id: String!
}

type Mutation {
	createPost(input: CreatePostInput!): Post
	updatePost(input: UpdatePostInput!): Post
	deletePost(input: DeletePostInput!): Post
}

type Post {
	author: String!
	id: String!
	url: String
	content: String
	title: String
}

type PostConnection {
	items: [Post]
	nextToken: String
}

type Query {
	getPost(id: String!, author: String!): Post
	listPosts(filter: TablePostFilterInput, limit: Int, nextToken: String): PostConnection
}

type Subscription {
	onCreatePost(
		author: String,
		id: String,
		url: String,
		content: String,
		title: String
	): Post
		@aws_subscribe(mutations: ["createPost"])
	onUpdatePost(
		author: String,
		id: String,
		url: String,
		content: String,
		title: String
	): Post
		@aws_subscribe(mutations: ["updatePost"])
	onDeletePost(
		author: String,
		id: String,
		url: String,
		content: String,
		title: String
	): Post
		@aws_subscribe(mutations: ["deletePost"])
}

input UpdatePostInput {
	author: String!
	id: String!
	url: String
}

Setup your Node.js project folder using this below package.json file:

{
  "name": "aws-appsync",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "apollo-cache-inmemory": "^1.1.0",
    "apollo-client": "^2.0.3",
    "apollo-link": "^1.0.3",
    "apollo-link-http": "^1.2.0",
    "aws-sdk": "^2.141.0",
    "aws-appsync": "^1.0.0",
    "es6-promise": "^4.1.1",
    "graphql": "^0.11.7",
    "graphql-tag": "^2.5.0",
    "isomorphic-fetch": "^2.2.1",
    "ws": "^3.3.1"
  }
}

touch two new files aws-exports.js and mutation.js file:

In aws-exports.js file,

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config = {
    "graphqlEndpoint": "end point url from aws appsync console",
    "region": "us-east-2", //your region
    "authenticationType": "API_KEY",
    "apiKey": "api key from aws appsync console",
    "ApiId": "api id from aws appsync console"
};
exports.default = config;

In mutation.js file start pasting the below code:

AWS config setup -

'use strict';
const aws_exports = require('./aws-export').default;
// CONFIG
const AppSync = {
    "graphqlEndpoint": aws_exports.graphqlEndpoint,
    "region": aws_exports.region,
    "authenticationType": aws_exports.authenticationType,
    "apiKey": aws_exports.apiKey,
};
const ApiId = aws_exports.ApiId;

Add polyfills for ws connections and connect aws appsync as below:

// POLYFILLS
global.WebSocket = require('ws');
global.window = global.window || {
    setTimeout: setTimeout,
    clearTimeout: clearTimeout,
    WebSocket: global.WebSocket,
    ArrayBuffer: global.ArrayBuffer,
    addEventListener: function () { },
    navigator: { onLine: true }
};
global.localStorage = {
    store: {},
    getItem: function (key) {
        return this.store[key]
    },
    setItem: function (key, value) {
        this.store[key] = value
    },
    removeItem: function (key) {
        delete this.store[key]
    }
};
require('es6-promise').polyfill();
require('isomorphic-fetch');

// Require AppSync module
const AUTH_TYPE = require('aws-appsync/lib/link/auth-link').AUTH_TYPE;
const AWSAppSyncClient = require('aws-appsync').default;

// INIT
// Set up AppSync client
const client = new AWSAppSyncClient({
    url: AppSync.graphqlEndpoint,
    region: AppSync.region,
    auth: {
        type: AUTH_TYPE.API_KEY,
        apiKey: AppSync.apiKey
    }
});

Now paste the follwing code and execute the query, the below is the a mutation which creates a new post

// GRAPHQL
const mutate = gql(`
  mutation createPost($createpostinput: CreatePostInput!) {
    createPost(input: $createpostinput) {
      author
      id
      url
      content
      title
    }
  }
`)

// APP CODE
client.hydrated().then(function (client) {
    // Now run a mutation
  const vari = {
      "author": "jk",
      "id": "1",
      "url": "thatcoder.space",
      "content": "Appsync content",
      "title": "appsync example"
  }

  client.mutate({ mutation: mutate, variables:{createpostinput: vari} })
    .then(function logData(data) {
        console.log('(Mutate): Inserting Data ----------->', data);
    })
    .catch(console.error);
});

Update Mutation

const mutate = gql(`
  mutation updatePost($updatepostinput: UpdatePostInput!) {
    updatePost (input: $updatepostinput) {
      author
      id
      url
      content
      title
    }
  }
`)

// APP CODE
client.hydrated().then(function (client) {
    // Now run a mutation
  const vari = {
      "author": "jk",
      "id": "1",
      "url": "thatcoder.space"
  }

  client.mutate({ mutation: mutate, variables:{updatepostinput: vari} })
    .then(function logData(data) {
        if(data) {
            console.log('(Mutate): updating Data ----------->', data);
        }
        else {
            console.log('Error!');
        }

    })
    .catch(console.error);
});

Final code:

AWS Appsync

Aws Appsync - example for query using node.js

Aws Appsync - example for mutation using node.js

Happy coding! 🙌