我想通过使用serverless-framework
来开发示例应用程序及其路由。我发送以下命令
sls create -t aws-nodejs-typescript -n sample-api-dev
生成如下目录
.
├── src
│ ├── functions # Lambda configuration and source code folder
│ │ ├── hello
│ │ │ ├── handler.ts # `Hello` lambda source code
│ │ │ ├── index.ts # `Hello` lambda Serverless configuration
│ │ │ ├── mock.json # `Hello` lambda input parameter, if any, for local invocation
│ │ │ └── schema.ts # `Hello` lambda input event JSON-Schema
│ │ │
│ │ └── index.ts # Import/export of all lambda configurations
│ │
│ └── libs # Lambda shared code
│ └── apiGateway.ts # API Gateway specific helpers
│ └── handlerResolver.ts # Sharable library for resolving lambda handlers
│ └── lambda.ts # Lambda middleware
│
├── package.json
├── serverless.ts # Serverless service file
├── tsconfig.json # Typescript compiler configuration
├── tsconfig.paths.json # Typescript paths
└── webpack.config.js # Webpack configuration
handler.ts
import type { ValidatedEventAPIGatewayProxyEvent } from '@libs/api-gateway';
import { formatJSONResponse } from '@libs/api-gateway';
import { middyfy } from '@libs/lambda';
import schema from './schema';
const hello: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (event) => {
return formatJSONResponse({
message: `Hello ${event.body.name}, welcome to the exciting Serverless world!`,
event,
});
};
export const main = middyfy(hello);
之后,我发送以下命令
sls local start
MAC0157:$ sls offline start
Running "serverless" from node_modules
Starting Offline at stage dev (us-east-1)
Offline [http for lambda] listening on http://localhost:3002
Function names exposed for local invocation by aws-sdk:
* hello: pricing-api-dev-dev-hello
┌─────────────────────────────────────────────────────────────────────────┐
│ │
│ POST | http://localhost:3000/dev/hello │
│ POST | http://localhost:3000/2015-03-31/functions/hello/invocations │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Server ready: http://localhost:3000 🚀
我的问题是
①如何在各个功能中设置路由?例如,我想在我的项目中添加GET
函数。我找不到如何在我的函数中设置路由。
hello/handler.ts
中POST
的定义在哪里?②如何改变环境?似乎离线从dev阶段(us-east-1)开始,我该如何改变这个阶段?是否需要设置?
如果有人有意见或材料,请告诉我。由于
感谢对于get请求,仍然可以使用相同的函数签名。
就这样写get request:
const getFunc: ValidatedEventAPIGatewayProxyEvent<typeof undefined> = async (event) => {
//Your function logic goes in here
return formatJSONResponse({
message: `Hello, welcome to the exciting Serverless world!`,
});
};
PS:当启动一个get请求时,不需要一个body request属性,根据我的理解,它是针对模式进行验证的;因此,您可以为模式类型指定undefined。