我想通过使用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 configurationhandler.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函数,我找不到如何在function.Where中设置路由,POST是在hello/handler.ts中定义的吗?
2如何改变环境?似乎离线开始在舞台开发(美-东-1),我如何改变这个阶段?需要设置什么环境吗?
如果有人有意见或资料,请告诉我。谢谢
谢谢
发布于 2022-10-10 10:17:04
对于get请求,仍然可以使用相同的函数签名。
只需按此方式为get请求编写:
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属性;因此,您只需为模式类型指定未定义的属性。
https://stackoverflow.com/questions/72949313
复制相似问题