如何将项目添加到列表? [英] How do i add items to a list?
问题描述
我想在用户表的 listOfVideosRated []
列表中添加一个字符串词。
I'd like to add a string word to the listOfVideosRated[]
list in my Users table.
推荐答案
如果您可以发布架构/解析器映射模板,我可以提供更具体的建议,但我会尽力回答您到目前为止已发布的内容。
If you can post your schema / resolver mapping template I can offer more specific advice, but I'll do my best to answer this with what you've posted so far.
如果您已经拥有现有商品,一种方法是更新现有的货币对并
If you have the existing item already, one way to do this would be to update the existing Pairs and pass that to your existing mutation.
const existingItem = {
id: "e5eb02ae-04d5-4331-91e6-11efaaf12ea5",
Pairs: [['a', 'b'],['c', 'd'],['e', 'f']]
}
const newPairs = {
number1: "g",
number2: "h"
}
const updateinfo = {
id: existingItem.id,
// Note that if existingItem.Pairs is always defined this can be simplified to
// Pairs: [...existingItem.Pairs, [newPairs.number1, newPairs.number2]]
Pairs: existingItem.Pairs ?
[...existingItem.Pairs, [newPairs.number1, newPairs.number2]] :
[[newPairs.number1, newPairs.number2]]
}
try {
await API.graphql(graphqlOperation (UpdateInfo, { input: updateinfo }))
//mutation
console.log('success')
}
catch (err) {
console.log(err)
}
使用DynamoDB函数
如果您没有现有项目,或者 Pairs
可能很大,则AWS DynamoDB的<可以改用code> list_append 函数。
Using DynamoDB functions
If you do not have the existing item or if Pairs
can be pretty big, AWS DynamoDB's list_append
function can be used instead.
list_append(操作数,操作数)
list_append (operand, operand)
此函数求值为一个列表,其中添加了新元素。您可以通过反转操作数的顺序将新元素追加到列表的开头或结尾。
This function evaluates to a list with a new element added to it. You can append the new element to the start or the end of the list by reversing the order of the operands.
这里是一个示例
### SDL
type Item {
id: ID!
Pairs: [[String]]
}
input AddPairInput {
id: ID!
number1: String!
number2: String!
}
type Mutation {
addPairToItem(input: AddPairInput!): Item!
}
...rest of schema omitted for brevity
### Resolver Request Mapping Template
{
"version": "2017-02-28",
"operation": "UpdateItem",
"key": {
"id": { "S": "$ctx.args.input.id"}
},
"update": {
### Note: we also use if_not_exists here so this works if Pairs is not yet defined on the item.
"expression":"SET Pairs = list_append(if_not_exists(Pairs, :emptyList), :newPair)",
"expressionValues":
{
":newPair":{"L": [{"L":[{"S":"$ctx.args.input.number1"},
{"S":"$ctx.args.input.number2"}]}]},
":emptyList":{"L": []}
}
}
}
### Resolver Response Mapping Template
$util.toJson($ctx.result)
这种方式也很好,因为如果有人更新对,您不会覆盖他们的更新。您还可以通过将参数的顺序反转为 list_append
函数,将新的Pair添加到列表的开头。
This way is also nice because if someone else updates Pairs, you won't overwrite their update. You can also add the new Pair to the beginning of the list by inverting the order of your arguments to the list_append
function.
如果您的项目是由AWS Amplify生成的,则需要添加客户解析器。
If your project was generated by AWS Amplify, you will need to add a customer resolver.
### ./amplify/backend/api/<api_name>/schema.graphql
type Item @model {
id: ID!
Pairs: [[String]]
}
type Mutation {
addPairToItem(input: AddPairToItemInput!): Item!
}
input AddPairToItemInput {
id: ID!
number1: String!
number2: String!
}
步骤2:添加解析器请求映射模板
Step 2: Add a resolver request mapping template
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addPairToItem.req.vtl
{
"version": "2017-02-28",
"operation": "UpdateItem",
"key": {
"id": { "S": "$ctx.args.input.id"}
},
"update": {
"expression":"SET Pairs = list_append(if_not_exists(Pairs, :emptyList), :newPair)",
"expressionValues":
{
":newPair":{"L": [{"L":[{"S":"$ctx.args.input.number1"},{"S":"$ctx.args.input.number2"}]}]},
":emptyList":{"L": []}
}
}
}
步骤3:添加解析器响应映射模板
Step 3: Add a resolver response mapping template
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addPairToItem.res.vtl
$util.toJson($ctx.result)
步骤4:添加自定义您的CustomResources堆栈的解析器
Step 4: Add your custom resolver to your CustomResources stack
### ./amplify/backend/api/<api_name>/stacks/CustomResources.json
"Resources": {
// ...other resources may exist here
"AddPairToItemResolver": {
"Type": "AWS::AppSync::Resolver",
"Properties": {
"ApiId": {
"Ref": "AppSyncApiId"
},
"DataSourceName": "ItemTable",
"TypeName": "Mutation",
"FieldName": "addPairToItem",
"RequestMappingTemplateS3Location": {
"Fn::Sub": [
"s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.addPairToItem.req.vtl",
{
"S3DeploymentBucket": {
"Ref": "S3DeploymentBucket"
},
"S3DeploymentRootKey": {
"Ref": "S3DeploymentRootKey"
}
}
]
},
"ResponseMappingTemplateS3Location": {
"Fn::Sub": [
"s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.addPairToItem.res.vtl",
{
"S3DeploymentBucket": {
"Ref": "S3DeploymentBucket"
},
"S3DeploymentRootKey": {
"Ref": "S3DeploymentRootKey"
}
}
]
}
}
}
},
步骤5:构建和部署您的网络w更改
- 运行
放大api gql-compile
以查看您的新更改生成的代码(可选)。 - 运行
放大推送
以部署您的更改。 - Run
amplify api gql-compile
to see the new changes in your generated code (optional). - Run
amplify push
to deploy your changes.
Step 5: Build and Deploy your new changes
现在,您可以运行放大api控制台
或使用新生成的代码来测试新变异的变化。
Now you can either run amplify api console
or use the new generated code to test the changes with your new mutation.
要生成新代码,可以运行 amplify codegen
。然后,您应该可以执行以下操作
To generate the new code you can run amplify codegen
. You should then be able to do something like this
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';
// Mutation
const addPairToItem = {
id: '1',
number1: 'a',
number2: 'b'
};
const newItem = await API.graphql(graphqlOperation(mutations.addPairToItem, {input: addPairToItem}));
其他示例
记住要更新您的具有添加的任何新解析器的CustomResources.json文件。
Additional Examples
Remember to update your CustomResources.json file with any new resolvers you add.
### ./amplify/backend/api/<api_name>/schema.graphql
type Item @model {
id: ID!
words: [String]
}
input AddWordInput {
id: ID!
word: String!
}
type Mutation {
addWordToItem(input: AddWordInput!): Item!
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordToItem.req.vtl
{
"version": "2017-02-28",
"operation": "UpdateItem",
"key": {
"id": { "S": "$ctx.args.input.id"}
},
"update": {
"expression":"SET words = list_append(if_not_exists(words, :emptyList), :newWord)",
"expressionValues":
{
":newWord":{"L": [{"S":"$ctx.args.input.word"}]},
":emptyList":{"L": []}
}
}
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordToItem.res.vtl
$util.toJson($ctx.result)
### Usage
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';
// Mutation
const newWord = {
id: '1',
word: 'foo'
};
const newItem = await API.graphql(graphqlOperation(mutations.addWordToItem, {input: newWord}));
将多个项目添加到标量值列表中
注意:我在这里介绍 $ util.dynamodb.toDynamoDBJson
来简化我们的VTL的构造。到目前为止,我很明确,但是该实用程序可以简化很多工作。 此处更多
Adding multiple items to a list of scalar values
Note: I am introducing $util.dynamodb.toDynamoDBJson
here to make constructing our VTL easier. I've been explicit thus far but this utility can simplify a lot of the work. More here
### ./amplify/backend/api/<api_name>/schema.graphql
type Item @model {
id: ID!
words: [String]
}
input AddWordsInput {
id: ID!
words: [String!]!
}
type Mutation {
addWordsToItem(input: AddWordsInput!): Item!
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordsToItem.req.vtl
{
"version": "2017-02-28",
"operation": "UpdateItem",
"key": {
"id": { "S": "$ctx.args.input.id"}
},
"update": {
"expression":"SET words = list_append(if_not_exists(words, :emptyList), :newWords)",
"expressionValues":
{
":newWords": $util.dynamodb.toDynamoDBJson($ctx.args.input.words),
":emptyList": $util.dynamodb.toDynamoDBJson([])
}
}
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordsToItem.res.vtl
$util.toJson($ctx.result)
### Usage
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';
// Mutation
const newWords = {
id: '1',
words: ["bar","xyz","bar"]
};
const newItem = await API.graphql(graphqlOperation(mutations.addWordsToItem, {input: newWords}));
从标量值列表中删除项目
从DynamoDB中的列表中删除元素是使用删除操作完成。您必须指定一个非负索引作为更新表达式的一部分。如果该项目上不存在索引,则您的请求将不会失败(例如,没有索引超出范围例外)。
Remove an item from a list of scalar values
Removing elements from lists in DynamoDB is done using the REMOVE action. You must specify a non-negative index as part of the update expression. If the index does not exist on the item, your request will not fail (e.g. no index out of bounds exceptions).
type Item @model {
id: ID!
words: [String]
}
input RemoveWordInput {
id: ID!
wordIndex: Int!
}
type Mutation {
removeWordFromItem(input: RemoveWordInput!): Item!
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.removeWordFromItem.req.vtl
{
"version": "2017-02-28",
"operation": "UpdateItem",
"key": {
"id": { "S": "$ctx.args.input.id"}
},
"update": {
"expression":"REMOVE words[$ctx.args.input.wordIndex]"
}
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.removeWordFromItem.res.vtl
$util.toJson($ctx.result)
### Usage
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';
// Mutation
const removeWord = {
id: '1',
// The index is 0 based so wordIndex: 0
// would delete the first item,
// wordIndex: 1 deletes the second, etc.
wordIndex: 1
};
const newItem = await API.graphql(graphqlOperation(mutations.removeWordFromItem, {input: removeWord}));
这篇关于如何将项目添加到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!