Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try to run ES module in a lambda function #13494

Closed
2 tasks done
loic-thomas opened this issue Dec 20, 2023 · 3 comments
Closed
2 tasks done

Try to run ES module in a lambda function #13494

loic-thomas opened this issue Dec 20, 2023 · 3 comments
Labels
functions Issues tied to the functions category pending-response Issue is pending response from the issue author pending-triage Issue is pending triage

Comments

@loic-thomas
Copy link

How did you install the Amplify CLI?

npm

If applicable, what version of Node.js are you using?

20.10.0

Amplify CLI Version

12.8.2

What operating system are you using?

Mac

Did you make any manual changes to the cloud resources managed by Amplify? Please describe the changes made.

No

Describe the bug

I try to run a function in lambda but it doesn't work.

I read some artices about it. Add type:module to the package.json, change extension or change it custom.js / custom.cjs... I tried many combinaisons in local and hosting env.

Here is my code

import fetch from 'node-fetch';
import stripePackage from 'stripe';

const stripe = stripePackage(process.env.STRIPE_SECRET_KEY);

export const handler = async (event) => {
  const GRAPHQL_ENDPOINT = process.env.API_ACGAREACTAPP_GRAPHQLAPIENDPOINTOUTPUT;
  const GRAPHQL_API_KEY = process.env.API_ACGAREACTAPP_GRAPHQLAPIKEYOUTPUT;

  const givenName = event.request.userAttributes.given_name;
  const familyName = event.request.userAttributes.family_name;

  // Combine given_name and family_name into a single string
  const fullName = `${givenName} ${familyName}`;

  try {
    const customer = await stripe.customers.create({
      email: event.request.userAttributes.email,
      name: fullName,
    });

    const stripeID = customer.id;

    const query = /* GraphQL */ `
      mutation CreateAcgaUser($input: CreateAcgaUserInput!) {
        createAcgaUser(input: $input) {
          userID
          stripeID
          family_name
          phone_number
          given_name
          email
        }
      }
    `;

    const variables = {
      input: {
        userID: event.userName,
        stripeID: stripeID,
        family_name: event.request.userAttributes.family_name,
        phone_number: event.request.userAttributes.phone_number,
        given_name: event.request.userAttributes.given_name,
        email: event.request.userAttributes.email,
      },
    };

    const response = await fetch(GRAPHQL_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': GRAPHQL_API_KEY,
      },
      body: JSON.stringify({
        query,
        variables,
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const responseBody = await response.json();
    console.log('responseBody', responseBody);

    return event;
  } catch (error) {
    console.error('Error during GraphQL mutation:', error);
    throw error;
  }
};

and my package.json
{
"name": "acgaPreSignup",
"type": "module",
"version": "2.0.0",
"description": "Lambda function generated by Amplify",
"main": "index.js",
"license": "Apache-2.0",
"devDependencies": {
"@types/aws-lambda": "^8.10.92"
},
"dependencies": {
"node-fetch": "^3.3.2",
"stripe": "^14.9.0"
}

Error displayed : "PreSignUp failed with error require is not defined in ES module scope, you can use import instead This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.."

Expected behavior

custom.js interpreted as .cjs file.
cf. :
https://aws.amazon.com/fr/blogs/compute/using-node-js-es-modules-and-top-level-await-in-aws-lambda/

Reproduction steps

Do what is described in the bug.

Project Identifier

No response

Log output

# Put your logs below this line
2023-12-20T02:06:22.295Z	undefined	ERROR	Uncaught Exception 	
{
    "errorType": "ReferenceError",
    "errorMessage": "require is not defined in ES module scope, you can use import instead\nThis file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
    "stack": [
        "ReferenceError: require is not defined in ES module scope, you can use import instead",
        "This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains \"type\": \"module\". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.",
        "    at file:///var/task/index.js:15:43",
        "    at Array.map (<anonymous>)",
        "    at file:///var/task/index.js:15:29",
        "    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"
    ]
}


Additional information

No response

Before submitting, please confirm:

  • I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.
  • I have removed any sensitive information from my code snippets and submission.
@loic-thomas loic-thomas added the pending-triage Issue is pending triage label Dec 20, 2023
@ykethan
Copy link
Member

ykethan commented Dec 20, 2023

Hey @loic-thomas, thank you for reaching out. Are you utilizing amplify mock function to run the function?
ES import are currently not supported on amplify mock function. A feature request is currently open on #10432
But we should be able to push function with type:module and test on the AWS console as support for this was added in Amplify CLI v10.2.3.

@ykethan ykethan added functions Issues tied to the functions category pending-response Issue is pending response from the issue author labels Dec 20, 2023
@josefaidt
Copy link
Contributor

Closing due to inactivity

@josefaidt josefaidt closed this as not planned Won't fix, can't repro, duplicate, stale Feb 2, 2024
Copy link

github-actions bot commented Feb 2, 2024

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
functions Issues tied to the functions category pending-response Issue is pending response from the issue author pending-triage Issue is pending triage
Projects
None yet
Development

No branches or pull requests

3 participants