通常,在 Amplify 上,您使用 AppSync 作为后端。
这样您就可以在 Amplify 上拥有全栈
使用 API,您可以轻松添加 API 的基本操作,并使用 lambda 自定义更具体的操作。
但如果您仍然需要自己托管,您可以为您的后端添加一个 lambda 函数,查看 this article 关于在 lambda 上运行 ExpressJS。
如果您通过Amplify-CLI (amplify function add) 添加它,您可以在 Amplify 控制台上看到它,包括日志和其他有关它的详细信息。
我将在下面更详细地介绍这两种情况:
使用 AppSync 的自定义操作
如果您决定将 DynamoDB/AppSync 与 GraphQL 接口一起使用,您可以在 GraphQL Schema 上定义您的自定义操作。
即:
- 创建一个 lambda 函数
MyCustomOperation
- 从你的操作中定义你想要的操作、输入和返回(你可以使用Javascript)
- 在您的 GraphQL 架构上,使用
@function 指令将函数与所需的查询相关联
type Query {
myCustomQuery(input: String): String @function(name: "MyCustomOperation-${env}")
}
查看更多详情here
快速后端
如果您需要完整的后端
要将其添加到您的 Amplify 项目中,您可以创建一个 lambda 函数
amplify function add 并选择模板Serverless express function (Integration with Amazon API Gateway),documentation 有更多详细信息。
它将提供您在下一步中提供的 API 端点。
您现在可以按照通知here在配置上手动设置它
Amplify.configure({
// OPTIONAL - if your API requires authentication
Auth: {
// REQUIRED - Amazon Cognito Identity Pool ID
identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',
// REQUIRED - Amazon Cognito Region
region: 'XX-XXXX-X',
// OPTIONAL - Amazon Cognito User Pool ID
userPoolId: 'XX-XXXX-X_abcd1234',
// OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
userPoolWebClientId: 'a1b2c3d4e5f6g7h8i9j0k1l2m3',
},
API: {
endpoints: [
{
name: "MyAPIGatewayAPI",
endpoint: "https://1234567890-abcdefgh.amazonaws.com"
},
{
name: "MyCustomCloudFrontApi",
endpoint: "https://api.my-custom-cloudfront-domain.com",
}
]
}
});
然后你只需要使用你已经拥有的后端代码来调整 lambda 函数。