我有一个 lambda 函数:
package org.smarter.note;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class AddNoteRequestHandler implements RequestHandler<NewNoteRequest, Note> {
private NoteRepository notes;
private LambdaLogger logger;
@Override
public Note handleRequest(NewNoteRequest newNote, Context context) {
init(context);
log("creating note: " + newNote.toJson());
notes.create(newNote);
return new Note();
}
private void log(String message) {
logger.log(String.format("%s\n", message));
}
private void init(Context context) {
this.logger = context.getLogger();
this.notes = new NoteRepository();
}
}
然后,当我使用 sam local 测试 lambda 并发送请求时:
{
"title": "hello",
"content": "body"
}
我期待 jsonNewNoteRequest
自动转换为,但它没有。这是日志:
You can now browse to the above endpoints to invoke your functions.
You do not need to restart/reload SAM CLI while working on your functions,
changes will be reflected instantly/automatically. You only need to restart
SAM CLI if you update your AWS SAM template.
2017/12/28 11:06:57 Invoking org.smarter.note.AddNoteRequestHandler (java8)
2017/12/28 11:06:57 Decompressing /Work/smarter-serverless/build/distributions/smarter-serverless.zip
2017/12/28 11:06:57 Mounting /private/var/folders/gv/m43y5g9x1xdc9f2kc2p0kpz00000gp/T/aws-sam-local-1514430417742696978 as /var/task:ro inside runtime container
START RequestId: bf0f77d3-198d-4211-ab9e-4c85a7c5de22 Version: $LATEST
creating note: {title=null, content=null}
我的山姆本地模板:
AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
notes:
Type: AWS::Serverless::Function
Properties:
Handler: org.smarter.note.AddNoteRequestHandler
CodeUri: ./build/distributions/smarter-serverless.zip
Runtime: java8
Events:
PostEvent:
Type: Api
Properties:
Path: /notes
Method: post
POJO:
package org.smarter.note;
import com.amazonaws.services.dynamodbv2.document.Item;
import java.util.HashMap;
import java.util.Map;
class NewNoteRequest implements DynamoDBItem, Json {
private String title;
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public Item item() {
return new Item()
.withString("title", this.title)
.withString("content", this.content);
}
@Override
public Map<String, Object> toJson() {
HashMap<String, Object> json = new HashMap<String, Object>();
json.put("title", this.title);
json.put("content", this.content);
return json;
}
}
依赖项还包括:
dependencies {
compile(
"com.amazonaws:aws-lambda-java-core:1.1.0",
"com.amazonaws:aws-lambda-java-events:1.1.0"
)
}
我不知道哪一部分是错的,AWS 文档说它可以直接进行映射。请帮忙。