Import Module error when deploying compiled typescript to lambda - node.js

I'm converting some of my JS code to typescript and when deploying using serverless framework to a lambda on AWS and running it i'm getting the below error. At first I thought one of my imports was bad but it looks like everything is as expected.
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'tslib'\nRequire stack:\n- /var/task/handlers/Create.js\n- >/var/runtime/UserFunction.js\n- /var/runtime/index.js",
"trace": [
"Runtime.ImportModuleError: Error: Cannot find module 'tslib'",
"Require stack:",
"- /var/task/handlers/Create.js",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object. (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:956:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)",
" at Module.load (internal/modules/cjs/loader.js:812:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:724:14)",
" at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)",
" at internal/main/run_main_module.js:17:11"
]
}
Serverless:
functions:
createFamily:
name: ${self:custom.createFamilyName}
handler: handlers/Create.createFamily
description: Lambda for Creating a family in the family service
timeout: 30
events:
- http:
path: /family
method: post
private: true
Handler:
import { APIGatewayEvent, Context, ProxyResult } from 'aws-lambda';
import { utilities } from '../handlers/utilities';
import { familyService } from '../services/FamilyService';
import { IFamily } from '../interfaces/IFamily';
let familyData: IFamily;
let serverReturn: IFamily;
export const createFamily = async (
event: APIGatewayEvent,
context: Context
): Promise<ProxyResult> => {
try {
if (!event.body) {
return utilities.BuildResponse(400, JSON.stringify('Object to create was not provided'));
}
familyData = JSON.parse(event.body);
serverReturn = await familyService.createFamily(familyData);
if (!serverReturn) {
return utilities.BuildResponse(404, JSON.stringify('Failed to create Family'));
}
return utilities.BuildResponse(201, JSON.stringify(serverReturn));
} catch(err) {
console.error('Family Service Create a family error: ', err);
return utilities.BuildResponse(500, JSON.stringify('Family Service internal server error'));
}
}

You need to compile your typescript down to javascript and reference the transpiled output in the template.

Related

HandlerNotFound at trigger aws lambda function

I have a problem with deployed to AWS Lambda function. I create an trigger to SQS queue, when I have new message then my trigger (index.receiver) processing this message. So, here is my code:
index.ts
import receiver from "./sqs/receiver";
exports.receiver = receiver;
sqs/receiver.ts
const receiver: SQSHandler = async (event) => {
//some logic
};
export default receiver;
After trigger this function, I see in AWS CloudWatch that nothing is working correctly and throw me this error:
{
"errorType": "Runtime.HandlerNotFound",
"errorMessage": "index.receiver is undefined or not exported",
"stack": [
"Runtime.HandlerNotFound: index.receiver is undefined or not exported",
" at Object.module.exports.load (/var/runtime/UserFunction.js:144:11)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:999:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)",
" at Module.load (internal/modules/cjs/loader.js:863:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:708:14)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)",
" at internal/main/run_main_module.js:17:47"
]
}
Here is also my project tree:
.serverless
node_modules
sqs
- receiver.ts
index.ts
package.json
serverless.yml
and serverless.yml
service: some-name
provider:
name: aws
runtime: nodejs12.x
region: eu-central-1
apiGateway:
minimumCompressionSize: 1024 # Enable gzip compression for responses > 1 KB
environment:
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1
# SQS Permission given
iamManagedPolicies:
- 'arn:aws:iam::aws:policy/AmazonSQSFullAccess'
functions:
receiver:
handler: index.receiver
events:
- sqs: <my-sqs-arn>
Can someone tell me what I'm doing wrong? Thanks for any help!
I resolve this problem. Problem was in this, that in my serverless.yml I point handler like this: handler: index.receiver but, when we use Typescript we should point it to dist/index.receiver because AWS can handle only JS files, we also need to remember about build project with this function before using serverless deploy.

Why Cannot find module 'request-promise' ? ( Runtime.ImportModuleError)

I create a simple NodeJS project and want to upload it as an aws lambda, but I get this error when I hit Test:
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'request-promise'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
"trace": [
"Runtime.ImportModuleError: Error: Cannot find module 'request-promise'",
"Require stack:",
"- /var/task/index.js",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:1085:14)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)",
" at Module.load (internal/modules/cjs/loader.js:950:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:790:14)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)",
" at internal/main/run_main_module.js:17:47"
]
}
I import every think, but the lambda can't find modules that already exist in node_modules.
the structure of my project is like this:
project_name>
node_modules
index.js
package.json
package-lock.json
index.js
let request = require("request-promise");
exports.handler = async () => {
// my functions
...
}
Do you have any idea how to solve this issue please!
I solved the issue by installing request
npm install request --save
then I deployed the project and it seems every thing is ok.

Curry.js error when exporting a rescript function with more than 1 parameter using genType

When exporting a function with more than 1 parameter (2 or more) it throws the following error, which basically says there is an issue with the way we import curry.js. I am attaching an example and package versions below.
Error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: path/to/node_modules/rescript/lib/es6/curry.js
require() of ES modules is not supported.
require() of /path/to/node_modules/rescript/lib/es6/curry.js from /path/to/src/demo.gen.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename curry.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /path/to/node_modules/rescript/lib/es6/package.json.
at new NodeError (node:internal/errors:329:5)
at Module._extensions..js (node:internal/modules/cjs/loader:1109:13)
at Object.require.extensions.<computed> [as .js] (/path/to/node_modules/ts-node/src/index.ts:851:44)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:996:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (/path/to/src/demo.gen.ts:6:1)
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Module.m._compile (/path/to/node_modules/ts-node/src/index.ts:858:23)
Example
demo.res
#genType
let helloWord = (firstName: string, lastName: string): unit => {
Js.log("Hello " ++ firstName ++ " " ++ lastName)
}
demo.bs.js
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
function helloWord(firstName, lastName) {
console.log("Hello " + firstName + " " + lastName);
}
exports.helloWord = helloWord;
/* No side effect */
demo.gen.ts
/* TypeScript file generated from demo.res by genType. */
/* eslint-disable import/first */
// #ts-ignore: Implicit any on import
import * as Curry__Es6Import from 'rescript/lib/es6/curry.js';
const Curry: any = Curry__Es6Import;
// #ts-ignore: Implicit any on import
import * as demoBS__Es6Import from './demo.bs';
const demoBS: any = demoBS__Es6Import;
export const helloWord: (firstName:string, lastName:string) => void = function (Arg1: any, Arg2: any) {
const result = Curry._2(demoBS.helloWord, Arg1, Arg2);
return result
};
package.json
{
"ts-node": "^10.2.1",
"gentype": "^4.1.0",
"rescript": "^9.1.4",
"typescript": "^3.9.6"
}
Node Version
$ node -v
v15.11.0
OS
Manjaro Linux
After taking a look at this file in genType: https://github.com/rescript-association/genType/blob/fb6201266558a64d62441f7ac0d8d6652456397a/src/Config_.ml
I found this option
{
"gentypeconfig": {
"module": "commonjs",
}
}
setting that solves the issue :D
I could not found it anywhere else in rescript docs unfortunately :(

Nuxt - Node error when I want to import some packages

I use Nuxt, and sometimes, when I want to use some npm packages, I have this error:
SyntaxError
Unexpected token '<'
The stack:
vm.js:102:7
new Script
internal/modules/cjs/loader.js:1114:10
Module._extensions..js
internal/modules/cjs/loader.js:950:32
Module.load
internal/modules/cjs/loader.js:790:14
Module._load
internal/modules/cjs/loader.js:974:19
Module.require
webpack:/external "vue-typeahead-bootstrap":1:
Object.vue-typeahead-bootstrap
webpack/bootstrap:25:
__webpack_require__
pages/account/tabs/addresses.js:693:81
Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./components/address/form/country.vue?vue&type=script&lang=js&
webpack/bootstrap:25:
I have this error for example on this package: vue-typeahead-bootstrap
If I import the package:
import VueTypeaheadBootstrap from ['vue-typeahead-bootstrap'](https://github.com/mattzollinhofer/vue-typeahead-bootstrap)
export default {
components: { VueTypeaheadBootstrap },
}
It throws the error.
Is it because the package is not supported or something ?
You may try to transpile it. https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-build#transpile
Add the package name like this
{
build: {
transpile: [
({ isServer }) => 'vue-typeahead-bootstrap'
]
}
}
As answered here: https://github.com/mattzollinhofer/vue-typeahead-bootstrap/issues/19#issuecomment-645510809

Runtime.ImportModuleError Error: Cannot find module 'axios/lib/utils' Serverless

I am using the Serverless framework. Backend as node.js. I have several microservices and all others are working fine, but now I have created now microservice where I have not used Axios but still, it is throwing error in the console.
One more issue is that in my local system it works perfectly, but as I push the same into the server then it starts creating issues.
This is the sample code which is throwing error
const { IamAuthenticator } = require('ibm-watson/auth');
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
async function textAnalyse(req, res) {
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2019-07-12',
authenticator: new IamAuthenticator({
apikey: 'API KEY'
}),
url: 'https://URL/natural-language-understanding/api'
});
const analyzeParams = {
'text': HtmlToText.fromString('Test text here'),
'features': {
'entities': {
'sentiment': true,
'limit': 100
}
}
};
const analysis = await naturalLanguageUnderstanding.analyze(analyzeParams);
// prepare the response object
res.send({ analysis: analysis });
}
Error in AWS Cloud watch
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'axios/lib/utils'",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'axios/lib/utils'",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:45:30)",
" at Module._compile (internal/modules/cjs/loader.js:778:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
" at Module.load (internal/modules/cjs/loader.js:653:32)",
" at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
" at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
" at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
" at startup (internal/bootstrap/node.js:283:19)",
" at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)"
]
}
I found the fixes for this.
when we call third-party API from our Lambda it requires the Axios to be implemented internally. So you need to create a folder that will have a package.json file with the dependency
"dependencies": {
"axios": "^0.19.2"
}
Then add the layer in the functions from AWS UI, left side menu
Then add the layer to your function
Now, by doing the above activity the issue will be resolved and Axios dependency is added successfully individually to the microservice.
Also, what you name the folders matters before zipping. Review these AWS docs for folder naming so you can import the library like you would in any other project.
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

Resources