简体   繁体   中英

Serverless with TypeScript, convert from plain JavaScript

I have a code in JavaScript that I want to convert to 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:

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.

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'",

You seemed to change your serverless.yml file between those two versions (vanilla javascript and typescript version).

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)

Serverless framework is build around plain javascript functions, that are deployed. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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