Appsync 'Batch Create' Resolver gives "mapping template" error - amazon-dynamodb

I'm trying to create a resolver for a BatchCreateIngredients mutation I created, but when I run the mutation I'm getting an error of type MappingTemplate and I'm not sure why.
My table's name is IngredientsTable and I'm not using any cognito verification.
The mutation:
mutation batchCreateIngredient {
batchCreateIngredients(
input: [
{name: "Cookie" vegan: VEGAN glutenfree: GLUTENFREE},
{name: "Pizza", vegan: VEGAN, glutenfree: GLUTENFREE},
]) {
items{
id
name
vegan
}
}
}
The error message:
{
"data": {
"batchCreateIngredients": null
},
"errors": [
{
"path": [
"batchCreateIngredients"
],
"data": null,
"errorType": "MappingTemplate",
"errorInfo": null,
"locations": [
{
"line": 6,
"column": 3,
"sourceName": null
}
],
"message": "Item list elements can't be null for table 'IngredientTable' at path '$[tables]'"
}
]
}
The Relevant Parts of My Schema:
input CreateIngredientInput {
name: String!
vegan: Vegan!
glutenfree: GlutenFree!
popularity: Int
}
enum GlutenFree {
GLUTENFREE
CONTAINS_GLUTEN
UNKNOWN
}
type Ingredient {
name: String!
id: ID!
vegan: Vegan
glutenfree: GlutenFree
popularity: Int
}
type IngredientConnection {
items: [Ingredient]
nextToken: String
}
type Mutation {
createIngredient(input: CreateIngredientInput!): Ingredient
batchCreateIngredients(input: [CreateIngredientInput]): IngredientConnection
updateIngredient(input: UpdateIngredientInput!): Ingredient
deleteIngredient(input: DeleteIngredientInput!): Ingredient
}
enum Vegan {
VEGAN
NON_VEGAN
UNKNOWN
}
The Resolver for BatchCreateIngredients:
#set($ingdata = [])
#foreach($ing in ${ctx.args.input})
$util.qr($ingdata.add($util.dynamodb.toMapValues($item)))
#end
{
"version" : "2018-05-29",
"operation" : "BatchPutItem",
"tables" : {
"IngredientTable": $utils.toJson($ingdata)
}
}

From what I can tell, it looks like the issue is in the request mapping template. You have called the loop variable $ing, but you are passing "$item" to the toMapValues function. Can you try changing "item" to "ing" ?

And also you are passing
{name: "Cookie" vegan: VEGAN glutenfree: GLUTENFREE}
but mapping
items{
id
name
vegan
}
glutenfree is missing and id is not handled in the resolver

Related

dynamodb add item to the array list

Using serverless-stack.
I have a table company with multiple branches:
new sst.Table(this, 'Company', {
fields: {
userId: sst.TableFieldType.STRING,
companyId: sst.TableFieldType.STRING,
companyName: sst.TableFieldType.STRING,
branches: [
{
branchId: sst.TableFieldType.STRING,
branchName: sst.TableFieldType.STRING
}
]
},
primaryIndex: {partitionKey: "userId", sortKey: "companyId"}
})
I am trying to add branch to the branches:
const branch = {
branchId: uuid.v1(),
branchName: data.branchName
}
const params = {
TableName: process.env.COMPANY_TABLE_NAME,
Key: {userId: "1", companyId: data.companyId},
UpdateExpression: "ADD #branches :branch",
ExpressionAttributeNames: { "#branches" : "branches" },
ExpressionAttributeValues: { ":branch": [branch] }
}
But I get this error:
ERROR ValidationException: Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: LIST, typeSet: ALLOWED_FOR_ADD_OPERAND
ValidationException: Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: LIST, typeSet: ALLOWED_FOR_ADD_OPERAND
ADD is only for numbers and sets. Your branches attribute is a list. So you can use SET with list_append.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET.UpdatingListElements
SET #branches = list_append(#branches, :branch) is correct. But ExpressionAttributeValues should be ExpressionAttributeValues: { ":branch": {"L":[branch]}}
You can refer to https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.update_item

AppSync batch insert to DynamoDB fails and returns null

I have the following resolver settings:
#set($questions = [])
#foreach($item in ${ctx.args.questions})
#set($item.id = $util.dynamodb.toDynamoDBJson($util.autoId()))
$util.qr($questions.add($util.dynamodb.toMapValues($item)))
#end
{
"version" : "2018-05-29",
"operation" : "BatchPutItem",
"tables" : {
"QuestionTable": $utils.toJson($questions)
}
}
And the following GraphQL schema:
input CreateQuestionInput {
text: String
sectionId: ID!
}
input CreateScoreInput {
score: Int!
questionId: ID!
userId: ID!
}
input CreateSectionInput {
title: String
subSection: String
}
input DeleteQuestionInput {
id: ID!
}
input DeleteScoreInput {
id: ID!
}
input DeleteSectionInput {
id: ID!
}
type Mutation {
...
createQuestion(input: CreateQuestionInput!): Question
batchCreateQuestion(questions: [CreateQuestionInput]!): [Question]
}
type Query {
getSection(id: ID!): Section
listSections(filter: TableSectionFilterInput, limit: Int, nextToken: String): SectionConnection
getScore(id: ID!): Score
listScores(filter: TableScoreFilterInput, limit: Int, nextToken: String): ScoreConnection
getQuestion(id: ID!): Question
listQuestions(filter: TableQuestionFilterInput, limit: Int, nextToken: String): QuestionConnection
}
type Question {
id: ID!
text: String
sectionId: ID!
}
type QuestionConnection {
items: [Question]
nextToken: String
}
type Schema {
query: Query
}
type Score {
id: ID!
score: Int!
questionId: ID!
userId: ID!
}
type ScoreConnection {
items: [Score]
nextToken: String
}
type Section {
id: ID!
title: String
subSection: String
questions: [Question]
}
type SectionConnection {
items: [Section]
nextToken: String
}
input TableQuestionFilterInput {
id: TableIDFilterInput
text: TableStringFilterInput
sectionId: TableIDFilterInput
}
input UpdateQuestionInput {
id: ID!
text: String
sectionId: ID
}
(I've redacted some of the schema as it was fairly large).
When I attempt to run the query:
mutation BatchCreateQuestions($sec: ID!) {
batchCreateQuestion(questions: [
{
text: "Tester 1"
sectionId: $sec
},
{
text: "Tester 2",
sectionId: $sec
}
]) {
id
text
sectionId
}
}
With the variables:
{ "sec": "abc123" }
I get the response:
{
"data": {
"batchCreateQuestion": [
null,
null
]
}
}
And when I check the DynamoDB table, it hasn't saved the values. I've granted full dynamodb permissions for this datasource, but still no joy.
Turns out I'd given batch write permissions to a similarly named role instead of the role affecting this data source. If you see a similar issue, check your IAM roles/permissions. Silly me.
What does your response template look like in the resolver? It should be $util.toJson($ctx.result.data.QuestionTable) based on the above table name being QuestionTable as that gets automatically translated into the response context.

API Gateway and DynamoDB PutItem for String Set

I can't seem to find how to correctly call PutItem for a StringSet in DynamoDB through API Gateway. If I call it like I would for a List of Maps, then I get objects returned. Example data is below.
{
"eventId": "Lorem",
"eventName": "Lorem",
"companies": [
{
"companyId": "Lorem",
"companyName": "Lorem"
}
],
"eventTags": [
"Lorem",
"Lorem"
]
}
And my example template call for companies:
"companies" : {
"L": [
#foreach($elem in $inputRoot.companies) {
"M": {
"companyId": {
"S": "$elem.companyId"
},
"companyName": {
"S": "$elem.companyName"
}
}
} #if($foreach.hasNext),#end
#end
]
}
I've tried to call it with String Set listed, but it errors out still and tells me that "Start of structure or map found where not expected" or that serialization failed.
"eventTags" : {
"SS": [
#foreach($elem in $inputRoot.eventTags) {
"S":"$elem"
} #if($foreach.hasNext),#end
#end
]
}
What is the proper way to call PutItem for converting an array of strings to a String Set?
If you are using JavaScript AWS SDK, you can use document client API (docClient.createSet) to store the SET data type.
docClient.createSet - converts the array into SET data type
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName:table,
Item:{
"yearkey": year,
"title": title
"product" : docClient.createSet(['milk','veg'])
}
};

nativescript firebase plugin, query by field

I am using nativescript-plugin-firebase to query firebase database in my angular2-nativescript application. I went through the documentation on how to query the database by field. For example I would like to fetch address of a user, based on uid for the below example database. But I could not find a way. Any help will be appreciated.
{
"address" : {
"-KfBtEuTA43UzSFfK7kU" : {
"house_number" : "hno1",
"street" : "street1",
"city" : "city1",
"uid" : "0P3Km5i9cEd1Akg7gJfJnALUSZw2"
},
"-KfC4Myo69bTZQCzw1yz" : {
"house_number" : "hno2",
"street" : "street2",
"city" : "city2",
"uid" : "4sj3ADekxsVNf5RaAFjbLbF6x0K2"
}
}
}
The following code gave me the query result by uid.
firebase.query(result => {
console.log("query result:", JSON.stringify(result));
}, "/address", {
orderBy: {
type: firebase.QueryOrderByType.CHILD,
value: 'uid'
},
ranges: [
{
type: firebase.QueryRangeType.START_AT,
value: uidValue
},
{
type: firebase.QueryRangeType.END_AT,
value: uidValue
}
]
})

Apollo/GraphQL: Setting Up Resolver for String Fields?

In GraphiQL at http://localhost:8080/graphiql, I'm using this query:
{
instant_message(fromID: "1"){
fromID
toID
msgText
}
}
I'm getting this response:
{
"data": {
"instant_message": {
"fromID": null,
"toID": null,
"msgText": null
}
},
"errors": [
{
"message": "Resolve function for \"instant_message.fromID\" returned undefined",
"locations": [
{
"line": 3,
"column": 5
}
]
},
{
"message": "Resolve function for \"instant_message.toID\" returned undefined",
"locations": [
{
"line": 4,
"column": 5
}
]
},
{
"message": "Resolve function for \"instant_message.msgText\" returned undefined",
"locations": [
{
"line": 5,
"column": 5
}
]
}
]
}
I tried to set up my system according to the examples found here:
https://medium.com/apollo-stack/tutorial-building-a-graphql-server-cddaa023c035#.s7vjgjkb7
Looking at that article, it doesn't seem to be necessary to set up individual resolvers for string fields, but I must be missing something.
What is the correct way to update my resolvers so as to return results from string fields? Example code would be greatly appreciated!
Thanks very much in advance to all for any thoughts or info.
CONNECTORS
import Sequelize from 'sequelize';
//SQL CONNECTORS
const db = new Sequelize(Meteor.settings.postgres.current_dev_system.dbname, Meteor.settings.postgres.current_dev_system.dbuser, Meteor.settings.postgres.current_dev_system.dbpsd, {
host: 'localhost',
dialect: 'postgres',
});
db
.authenticate()
.then(function(err) {
console.log('Connection to Sequelize has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the Sequelize database:', err);
});
const IMModel = db.define('IM', {
id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
fromID: {type: Sequelize.STRING},
toID: {type: Sequelize.STRING},
msgText: {type: Sequelize.STRING}
});
IMModel.sync({force: true}).then(function () {
// Table created
return IMModel.create({
fromID: '1',
toID: '2',
msgText: 'msg set up via IMModel.create'
});
});
const IM = db.models.IM;
export {db, IM };
SCHEMA
const typeDefinitions = [`
type instant_message {
id: Int
fromID: String
toID: String
msgText: String
}
type Query {
instant_message(fromID: String, toID: String, msgText: String): instant_message
}
type RootMutation {
createInstant_message(
fromID: String!
toID: String!
msgText: String!
): instant_message
}
schema {
query: Query,
mutation: RootMutation
}
`];
export default typeDefinitions;
RESOLVERS
import * as connectors from './db-connectors';
import { Kind } from 'graphql/language';
const b = 100;
const resolvers = {
Query: {
instant_message(_, args) {
const a = 100;
return connectors.IM.find({ where: args });
}
},
RootMutation: {
createInstant_message: (__, args) => { return connectors.IM.create(args); },
},
};
export default resolvers;
When you define your GraphQLObjectTypes you need to provide a resolver for each of their fields.
You defined your instant_message with multiple fields but did not provide resolvers for each of these fields.
More over you defined the types of those field with regular typescript fields while you need to define it with GraphQL types (GraphQLInt, GraphQLString, GrapQLFloat etc..)
So defining your type should look something like this:
let instant_message = new GraphQLObjectType({
id: {
type: GraphQLInt,
resolve: (instantMsg)=> {return instantMsg.id}
}
fromID: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.fromID}
}
toID: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.toID}
}
msgText: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.msgText}
}
})
In addition, you will need to define your Query as follows:
let Query = new GraphQLObjectType({
name: "query",
description: "...",
fields: () => ({
instant_messages: {
type: new GraphQLList(instant_message),
args: {
id: {type: GraphQLInt}
},
resolve: (root, args) => {
connectors.IM.find({ where: args })
}
}
})
})
The issue is that the query does not expect an array,
Please fix it:
type Query {
instant_message(fromID: String, toID: String, msgText: String): [instant_message]
}
Then you should make sure the resolver returns Array of objects, if it doesnt work then the resolver is not returning an Array.

Resources