简体   繁体   English

使用 TypeScript 实现无服务器,从纯 JavaScript 转换

[英]Serverless with TypeScript, convert from plain JavaScript

I have a code in JavaScript that I want to convert to TypeScript我有一段 JavaScript 代码,我想将其转换为 TypeScript

Currently I have this two files:目前我有这两个文件:

API_Responses.js

const Responses = {
  _200(data = {}) {
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  }
};

module.exports = Responses;

getData.js

const Responses = require('./API_Responses');

exports.handler = async event => {
    const response = {
      payload: event?.pathParameters || ''
    }

    return Responses._200(response);
};

And the serverles.yml file to deploy that lambda function is:用于部署该 lambda 函数的serverles.yml文件是:

functions:
  getData:
    handler: getData.handler
    events:
      - http:
          path: get-data/{ID}
          method: GET
          cors: true

I want to use ts files and import ES6 methods.我想使用ts文件并import ES6 方法。

So I tried this changes:所以我尝试了这个改变:

API_Responses.ts

export const Responses = {
  _200(data = {}) {
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  }
};

getData.ts

import Responses from './API_Responses';

// But here I'm confused
const handler = async event => {
    const response = {
      payload: event?.pathParameters || ''
    }

    return Responses._200(response);
};

export default handler;

serverless.yml

functions:
  getData:
    handler: getData.handler
    events:
      - http:
          path: get-data/{ID}
          method: GET
          cors: true

With this way I get the error: "Runtime.ImportModuleError: Error: Cannot find module 'getData'",通过这种方式我得到错误:“Runtime.ImportModuleError:错误:找不到模块'getData'”,

You seemed to change your serverless.yml file between those two versions (vanilla javascript and typescript version).您似乎在这两个版本(vanilla javascript 和 typescript 版本)之间更改了serverless.yml文件。

The name of the function that is called is still "handler", yet in the serverless.yml file you are calling "getData" (corresponding to the file name)被调用的函数的名称仍然是“handler”,但在serverless.yml文件中你调用的是“getData”(对应于文件名)

Serverless framework is build around plain javascript functions, that are deployed.无服务器框架是围绕已部署的普通 JavaScript 函数构建的。 It doesn't know about your filenames once its compiled.编译后它不知道您的文件名。

If you are using ts-node or if you are compiling your .ts files manually, you can always check the generated output source code, that will be executed.如果您使用 ts-node 或手动编译.ts文件,您可以随时检查生成的输出源代码,该代码将被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM