问:
I am getting this error: getFCMToken error ReferenceError: navigator is not defined when implementing push notification in nodeJs with firebase
I am getting this error while trying to implement push notification in nodeJs with firebase.
I have followed the documentation and am still getting this error. What could the problem be?
I will need help with this.

```<code>getFCMToken error ReferenceError: navigator is not defined
    at /Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/@firebase/messaging/src/api/getToken.ts:30:3
    at step (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:144:27)
    at Object.next (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:125:57)
    at /Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:118:75
    at new Promise (<anonymous>)
    at Object.__awaiter (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:114:16)
    at _getToken (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/@firebase/messaging/dist/index.cjs.js:1147:18)
    at /Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/@firebase/messaging/src/api.ts:114:10
    at step (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:144:27)
    at Object.next (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:125:57)
</code>```

I am trying to get a FCMToken to allow me send a push notification.

This is the code I have written but don't know what am doing wrong here.

```<code>import admin from "firebase-admin";
const { getMessaging, getToken } = require("firebase/messaging");

const serviceAccount = require("./src/serviceAccount.json");
const webPush = require('web-push');

// Generate a VAPID key pair
const vapidKeys = webPush.generateVAPIDKeys();

console.log('Public key:', vapidKeys.publicKey);
console.log('Private key:', vapidKeys.privateKey);

// Initialize the Firebase Admin SDK with the service account key file
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://notification-service-32997.nam5.firebaseio.com'
});

console.log("admin", admin);

// Define the notification payload
const payload = {
  notification: {
    title: "Hello, World!",
    body: "This is a test push notification",
  },
};

const messaging = admin.messaging();

(async function () {
  try {
    // Don't forget to paste your VAPID key here
    // (you can find it in the Console too)
    const token = await getToken({
      vapidKey: vapidKeys.publicKey,
    });
    // const token = await messaging.tokenManager.getToken({
    //   vapidKey: process.env.PUBLIC_KEY,
    // });
    console.log("token", token)
    return token;
  } catch (e) {
    console.log("getFCMToken error", e);
    return undefined;
  }
})();
</code>```

Body:
I am getting this error while trying to implement push notification in nodeJs with firebase.
I have followed the documentation and am still getting this error. What could the problem be?
I will need help with this.

getFCMToken error ReferenceError: navigator is not defined
    at /Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/@firebase/messaging/src/api/getToken.ts:30:3
    at step (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:144:27)
    at Object.next (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:125:57)
    at /Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:118:75
    at new Promise (<anonymous>)
    at Object.__awaiter (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:114:16)
    at _getToken (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/@firebase/messaging/dist/index.cjs.js:1147:18)
    at /Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/@firebase/messaging/src/api.ts:114:10
    at step (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:144:27)
    at Object.next (/Users/decagon/Desktop/IGate System Projects/Errand Joe/Notification/node_modules/tslib/tslib.js:125:57)

I am trying to get a FCMToken to allow me send a push notification.

This is the code I have written but don't know what am doing wrong here.

import admin from "firebase-admin";
const { getMessaging, getToken } = require("firebase/messaging");

const serviceAccount = require("./src/serviceAccount.json");
const webPush = require('web-push');

// Generate a VAPID key pair
const vapidKeys = webPush.generateVAPIDKeys();

console.log('Public key:', vapidKeys.publicKey);
console.log('Private key:', vapidKeys.privateKey);

// Initialize the Firebase Admin SDK with the service account key file
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://notification-service-32997.nam5.firebaseio.com'
});

console.log("admin", admin);

// Define the notification payload
const payload = {
  notification: {
    title: "Hello, World!",
    body: "This is a test push notification",
  },
};

const messaging = admin.messaging();

(async function () {
  try {
    // Don't forget to paste your VAPID key here
    // (you can find it in the Console too)
    const token = await getToken({
      vapidKey: vapidKeys.publicKey,
    });
    // const token = await messaging.tokenManager.getToken({
    //   vapidKey: process.env.PUBLIC_KEY,
    // });
    console.log("token", token)
    return token;
  } catch (e) {
    console.log("getFCMToken error", e);
    return undefined;
  }
})();


来源: stackexchange

问:
web3.min.js undescriptible bug
i'm working on a react project and when I run it with npm run start from react-scripts it works but when i use npm run build and test it on a local express server, i got this :

```<code>Uncaught TypeError: Super expression must either be null or a function
    i web3.min.js:25038
    l web3.min.js:25037
    i web3.min.js:25036
    exports web3.min.js:25192
    exports web3.min.js:25193
    r web3.min.js:13
    exports web3.min.js:24116
    r web3.min.js:13
    exports web3.min.js:19276
    r web3.min.js:13
    exports web3.min.js:3847
    r web3.min.js:13
    exports web3.min.js:19238
    r web3.min.js:13
    exports web3.min.js:48
    <anonymous> web3.min.js:49
    f account:1
    423 Bet.jsx:20
    f account:1
    200 walletconnect.png:1
    f account:1
    a account:1
    e account:1
    <anonymous> main.f01fcd85.chunk.js:1
</code>```

I already used npm run build to test in production my project but now i can't find what's wrong...

I tried to remove the react component involved (Bet.jsx), I tried to update web3js and I tried an older version of my project to make sure my backend works

ContentLicense: CC BY-SA 4.0

Title: web3.min.js undescriptible bug

Body:
i'm working on a react project and when I run it with npm run start from react-scripts it works but when i use npm run build and test it on a local express server, i got this :

Uncaught TypeError: Super expression must either be null or a function
    i web3.min.js:25038
    l web3.min.js:25037
    i web3.min.js:25036
    exports web3.min.js:25192
    exports web3.min.js:25193
    r web3.min.js:13
    exports web3.min.js:24116
    r web3.min.js:13
    exports web3.min.js:19276
    r web3.min.js:13
    exports web3.min.js:3847
    r web3.min.js:13
    exports web3.min.js:19238
    r web3.min.js:13
    exports web3.min.js:48
    <anonymous> web3.min.js:49
    f account:1
    423 Bet.jsx:20
    f account:1
    200 walletconnect.png:1
    f account:1
    a account:1
    e account:1
    <anonymous> main.f01fcd85.chunk.js:1

I already used npm run build to test in production my project but now i can't find what's wrong...

I tried to remove the react component involved (Bet.jsx), I tried to update web3js and I tried an older version of my project to make sure my backend works


问:
How to use Google Recaptchav.3 in Nuxtjs v.3
I want to use Google Recaptcha without using any external library in Nuxt3, this is sign-in page script section

```
<p>and the template section</p>
<pre class="lang-html prettyprint-override"><code><template>
  <button class="g-recaptcha"
    data-sitekey="6LfJox8gAAAAADKdDuAYHZqpvkRmArUzyWv"
    data-callback="onSubmit"
    data-action="submit"
  >
    Submit
  </button>
</template>
</code>```

then when I click on the Submit button, I have the following error

ReCAPTCHA couldn't find user-provided function: onSubmit

Body:
I want to use Google Recaptcha without using any external library in Nuxt3, this is sign-in page script section

and the template section

<template>
  <button class="g-recaptcha"
    data-sitekey="6LfJox8gAAAAADKdDuAYHZqpvkRmArUzyWv"
    data-callback="onSubmit"
    data-action="submit"
  >
    Submit
  </button>
</template>

then when I click on the Submit button, I have the following error

ReCAPTCHA couldn't find user-provided function: onSubmit


问:
Error creating 3 different graphics in the same png file using gnuplot and java.lang.Runtime and without any Library

public static void main(String[] args) throws IOException, InterruptedException {
        // Set up the gnuplot command and arguments
        String[] cmd = {"gnuplot", "-e",
                "set terminal png; set output 'plotS.png'; plot 'graficoS.txt' using 1:2 with lines"};
        String[] cmd2 = {"gnuplot", "-e",
                "set terminal png; set output 'plotS.png'; replot 'graficoI.txt' using 1:3 with lines"};
        String[] cmd3 = {"gnuplot", "-e",
                "set terminal png; set output 'plotS.png'; replot 'graficoR.txt' using 1:4 with lines"};

        // Start the processes
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
        Process process2 = Runtime.getRuntime().exec(cmd2);
        process2.waitFor();
        Process process3 = Runtime.getRuntime().exec(cmd3);
        process3.waitFor();

        // Read the output from the processes
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
}
```

Not showing nothing on the png file , even the gnuplot graphic. In different png files its working , but in the same it isn't.

Body:
public static void main(String[] args) throws IOException, InterruptedException {
        // Set up the gnuplot command and arguments
        String[] cmd = {"gnuplot", "-e",
                "set terminal png; set output 'plotS.png'; plot 'graficoS.txt' using 1:2 with lines"};
        String[] cmd2 = {"gnuplot", "-e",
                "set terminal png; set output 'plotS.png'; replot 'graficoI.txt' using 1:3 with lines"};
        String[] cmd3 = {"gnuplot", "-e",
                "set terminal png; set output 'plotS.png'; replot 'graficoR.txt' using 1:4 with lines"};

        // Start the processes
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
        Process process2 = Runtime.getRuntime().exec(cmd2);
        process2.waitFor();
        Process process3 = Runtime.getRuntime().exec(cmd3);
        process3.waitFor();

        // Read the output from the processes
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
}

Not showing nothing on the png file , even the gnuplot graphic. In different png files its working , but in the same it isn't.


问:
Expo eas build android aap error: [stderr] npm ERR! code ERESOLVE
I'm facing an error while using eas in expo to build android .aab bundle.

The expo app is running correctly on expo with all dependencies installed. But, when executing:
eas build -p android

The expo shows an error:

```<code>Running "npm install" in the root dir of your repository
[stderr] npm ERR! code ERESOLVE
[stderr] npm ERR!
[stderr] ERESOLVE could not resolve
[stderr] npm ERR!
[stderr] npm ERR! While resolving: react-native-elements@3.4.2
[stderr] npm ERR! Found: react-native-safe-area-context@4.4.1
[stderr] npm ERR! node_modules/react-native-safe-area-context
[stderr] npm
[stderr] ERR!   react-native-safe-area-context@"4.4.1" from the root project
[stderr] npm ERR!   peer react-native-safe-area-context@">= 3.0.0" from @react-navigation/elements@1.3.6
[stderr] npm ERR!   node_modules/@react-navigation/elements
[stderr] npm ERR!     @react-navigation/elements@"^1.3.6" from @react-navigation/stack@6.3.4
[stderr] npm ERR!     node_modules/@react-navigation/stack
[stderr] npm ERR!       @react-navigation/stack@"^6.3.4" from the root project
[stderr] npm ERR!   2 more (@react-navigation/stack, @rneui/base)
[stderr] npm ERR!
[stderr] npm ERR! Could not resolve dependency:
[stderr] npm ERR! peer react-native-safe-area-context@"^3.1.9" from react-native-elements@3.4.2
[stderr] npm ERR! node_modules/react-native-elements
[stderr] npm ERR!   react-native-elements@"^3.4.2" from the root project
[stderr] npm ERR!
[stderr] npm ERR! Conflicting peer dependency: react-native-safe-area-context@3.4.1
[stderr] npm ERR! node_modules/react-native-safe-area-context
[stderr] npm
[stderr] ERR!   peer react-native-safe-area-context@"^3.1.9" from react-native-elements@3.4.2
[stderr] npm ERR!   node_modules/react-native-elements
[stderr] npm ERR!     react-native-elements@"^3.4.2" from the root project
[stderr] npm ERR!
[stderr] npm ERR! Fix the upstream dependency conflict, or retry
[stderr] npm ERR! this command with --force, or --legacy-peer-deps
[stderr] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
[stderr] npm ERR!
[stderr] npm ERR! See /home/expo/.npm/eresolve-report.txt for a full report.
[stderr]
[stderr] npm ERR! A complete log of this run can be found in:
[stderr] npm ERR!     /home/expo/.npm/_logs/2022-12-17T19_35_38_310Z-debug-0.log
npm exited with non-zero code: 1
</code>```

I've tried to install legacy-peer-deps (npm install --legacy-peer-deps). I also tried to put as a dependency ("legacy-peer-deps":"^7.24.2") on package.json.

Any further suggestion? Thank you in advance.

Body:
I'm facing an error while using eas in expo to build android .aab bundle.

The expo app is running correctly on expo with all dependencies installed. But, when executing:
eas build -p android

The expo shows an error:

Running "npm install" in the root dir of your repository
[stderr] npm ERR! code ERESOLVE
[stderr] npm ERR!
[stderr] ERESOLVE could not resolve
[stderr] npm ERR!
[stderr] npm ERR! While resolving: react-native-elements@3.4.2
[stderr] npm ERR! Found: react-native-safe-area-context@4.4.1
[stderr] npm ERR! node_modules/react-native-safe-area-context
[stderr] npm
[stderr] ERR!   react-native-safe-area-context@"4.4.1" from the root project
[stderr] npm ERR!   peer react-native-safe-area-context@">= 3.0.0" from @react-navigation/elements@1.3.6
[stderr] npm ERR!   node_modules/@react-navigation/elements
[stderr] npm ERR!     @react-navigation/elements@"^1.3.6" from @react-navigation/stack@6.3.4
[stderr] npm ERR!     node_modules/@react-navigation/stack
[stderr] npm ERR!       @react-navigation/stack@"^6.3.4" from the root project
[stderr] npm ERR!   2 more (@react-navigation/stack, @rneui/base)
[stderr] npm ERR!
[stderr] npm ERR! Could not resolve dependency:
[stderr] npm ERR! peer react-native-safe-area-context@"^3.1.9" from react-native-elements@3.4.2
[stderr] npm ERR! node_modules/react-native-elements
[stderr] npm ERR!   react-native-elements@"^3.4.2" from the root project
[stderr] npm ERR!
[stderr] npm ERR! Conflicting peer dependency: react-native-safe-area-context@3.4.1
[stderr] npm ERR! node_modules/react-native-safe-area-context
[stderr] npm
[stderr] ERR!   peer react-native-safe-area-context@"^3.1.9" from react-native-elements@3.4.2
[stderr] npm ERR!   node_modules/react-native-elements
[stderr] npm ERR!     react-native-elements@"^3.4.2" from the root project
[stderr] npm ERR!
[stderr] npm ERR! Fix the upstream dependency conflict, or retry
[stderr] npm ERR! this command with --force, or --legacy-peer-deps
[stderr] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
[stderr] npm ERR!
[stderr] npm ERR! See /home/expo/.npm/eresolve-report.txt for a full report.
[stderr]
[stderr] npm ERR! A complete log of this run can be found in:
[stderr] npm ERR!     /home/expo/.npm/_logs/2022-12-17T19_35_38_310Z-debug-0.log
npm exited with non-zero code: 1

I've tried to install legacy-peer-deps (npm install --legacy-peer-deps). I also tried to put as a dependency ("legacy-peer-deps":"^7.24.2") on package.json.

Any further suggestion? Thank you in advance.


问:
Catia V5 VB.net code, control instance name
I have a Catia V5 Product inside another product :

The following code allows me to add a new part called "PART_NAME" inside the main "Product1" (Note that 2 lines are commented) :

```<code>    Dim CATIA = GetObject(, "CATIA.Application")
    Dim documents1 = CATIA.Documents
    Dim productDocument1 = CATIA.ActiveDocument

    Dim product1 = productDocument1.Product
    Dim products1 = product1.Products

    'Dim product2 = products1.Item("Product2.1")
    'Dim products2 = product2.Products

    Dim product3 = products1.AddNewComponent("Part", "")
    product3.Name = "PART_NAME"
</code>```

The result is the following  :

Now I would like to add this part but inside "Product2.1". I then execute the same code, but uncomment everything and slightly change the last two code lines :

```<code>    Dim CATIA = GetObject(, "CATIA.Application")
    Dim documents1 = CATIA.Documents
    Dim productDocument1 = CATIA.ActiveDocument

    Dim product1 = productDocument1.Product
    Dim products1 = product1.Products

    Dim product2 = products1.Item("Product2.1")
    Dim products2 = product2.Products

    Dim product3 = products2.AddNewComponent("Part", "")
    product3.Name = "PART_NAME_2"
</code>```

The result is the following :

The part is indeed added but not renamed correctly.
Why ?

Body:
I have a Catia V5 Product inside another product :

The following code allows me to add a new part called "PART_NAME" inside the main "Product1" (Note that 2 lines are commented) :

    Dim CATIA = GetObject(, "CATIA.Application")
    Dim documents1 = CATIA.Documents
    Dim productDocument1 = CATIA.ActiveDocument

    Dim product1 = productDocument1.Product
    Dim products1 = product1.Products

    'Dim product2 = products1.Item("Product2.1")
    'Dim products2 = product2.Products

    Dim product3 = products1.AddNewComponent("Part", "")
    product3.Name = "PART_NAME"

The result is the following  :

Now I would like to add this part but inside "Product2.1". I then execute the same code, but uncomment everything and slightly change the last two code lines :

    Dim CATIA = GetObject(, "CATIA.Application")
    Dim documents1 = CATIA.Documents
    Dim productDocument1 = CATIA.ActiveDocument

    Dim product1 = productDocument1.Product
    Dim products1 = product1.Products

    Dim product2 = products1.Item("Product2.1")
    Dim products2 = product2.Products

    Dim product3 = products2.AddNewComponent("Part", "")
    product3.Name = "PART_NAME_2"

The result is the following :

The part is indeed added but not renamed correctly.
Why ?


问:
Azure Cosmosdb query runs fine in portal but not in text string
My query string is propperly escaped:

```<code>"g.addV('planet').property('name','D\\PA')
  .property('class','terrestrial')
  .property('objid','2875301669077')
  .property('label','planet')
  .property('radius',0.0814)
  .property('mass',0.9808)
  .property('isSupportsLife','True')
  .property('isPopulated','True')
  .property('isHomeworld','True')
  .property('username','BillmanLocal2')
  .property('objtype','planet')"
</code>```

Running the same query in the portal seems fine:

But running it as a string in callback = self.c.submitAsync(query) fashion causes the exception:

```<code>GraphSyntaxException
Gremlin query syntax error: Unexpected token: ; in input: 'g.addV('planet').property('name',''. @ line 1, column 34.
</code>```

Is it possible that Azure's Cosmos is doing some cleaning in the process?

Body:
My query string is propperly escaped:

"g.addV('planet').property('name','D\\PA')
  .property('class','terrestrial')
  .property('objid','2875301669077')
  .property('label','planet')
  .property('radius',0.0814)
  .property('mass',0.9808)
  .property('isSupportsLife','True')
  .property('isPopulated','True')
  .property('isHomeworld','True')
  .property('username','BillmanLocal2')
  .property('objtype','planet')"

Running the same query in the portal seems fine:

But running it as a string in callback = self.c.submitAsync(query) fashion causes the exception:

GraphSyntaxException
Gremlin query syntax error: Unexpected token: ; in input: 'g.addV('planet').property('name',''. @ line 1, column 34.

Is it possible that Azure's Cosmos is doing some cleaning in the process?


问:
How to Pipeline File Lines in NodeJS
I am new to programming NodeJS and want to load multi-line sections from a file into MongoDB. I have seen simple solution that reads the file into memory and parses into lines. This will fill my need but doesn't seem the "NodeJS" way of doing it. If I just wanted to quickly load the file, I would load IntelliJ and do it in Java. I want to learn asynchronous and pipelines.

I see the the basic steps are stream the file in chunks, parse the chunks into lines, group lines into sections, convert sections into JSON, and insert JSON into MongoDB.

I like the idea of pipelines since I can easily replace parts and reuse others. It also helps in this case since the slowest step is the last and the whole input file could be loaded into memory before the first MongoDB document is written.

I have searched for a good example but they seem to be missing parts and explanations of what I need to modify. I have seen you can easily pipe a file stream in chunks but I need lines. I have seen you can easily stream a file to a line parser but that is not a pipeline.

Any ideas on how to do this or good examples?

Thanks,
Wes.

Title: How to Pipeline File Lines in NodeJS


问:
How to create a function that returns new session format with extra key value pair
I am using NextJS with NextAuth with google and email providers. Unfortunately, the session returns only few fields that does not include userId of the user from the database.

I created however a function that I intend to use with every getServerSideProps request. The function returns the following:

```<code>{
  user: {
    name: 'daniel sas',
    email: 'emailofuser@gmail.com',
    image: 'https://lh3.gooleusercontent.com/a/AEdFTp6r44ZwqcfJORNnuYtbVv_LYbab-wv5Uyxk=s96-c',
    userId: 'clbcpc0hi0002sb1wsiea3q5d'
  },
  expires: '2022-12-17T20:18:52.580Z'
}
</code>```

The problem is I am getting an error that does not allow me to pass the props in the page:

```<code>Error: Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?
</code>```

In the function I get the user by the email, and attach the userId.

```<code>import { getSession } from "next-auth/react";
import prisma from './prisma'

// This function get the email and returns a new session object that includes
//  the userId

export const requireAuthentication = async context => {
    const session = await getSession(context);

    const errorOrUserNotFound = () => {
      return {
        redirect: {
          destination: '/signup',
          permanent: false
        }
      }
    }

    // If there is no user or there is an error ret to signup page
    if (!session) {
        errorOrUserNotFound();
    }

    // If the user is not found return same redirect to signup
    else {
        try {
            const user = await prisma.user.findUnique({where: { email: session.user.email }});

            if (!user) return errorOrUserNotFound();

            // Must return a new session here that contains the userId...
            else {
              const newSession = {
                user: {
                  ...session.user,
                  userId: user.id
                },

                expires: session.expires
              };

              console.log(newSession);

              return {
                props: {
                  session: newSession
                }
              }
            }
        }
        catch (error) {
            if (error) {
              console.log(error);
            }
        }
    }
}
</code>```

The react component looks like this. In the getServerSideProps i return the await function. The problem is that when I log the prop in the serverside, I get the following:

```<code>{
  props: { session: { user: [Object], expires: '2022-12-17T20:18:52.580Z' } }
}
</code>```

However, if i log the props in the clientside, I get an empty object...

```<code>//Clientside compoen
import { getSession } from "next-auth/react"
import { Fragment, useState } from "react";
import { requireAuthentication } from "../../lib/requireAuthentication";
import CreateListModal from "./CreateListModal";

const DashboardPage = props => {

  const [loading, setloading] = useState(false);

  console.log(props);

  return (
    <section className="border-4 border-orange-800 max-w-5xl mx-auto">

      <CreateListModal userId={props.userId} loading={loading} setloading={setloading} />
    </section>
  )
}

export const getServerSideProps = async context => {
  const session = await getSession(context);

  const reqAuth = await requireAuthentication(context);
  console.log(reqAuth);

  return reqAuth
}

export default DashboardPage;
</code>```

Body:
I am using NextJS with NextAuth with google and email providers. Unfortunately, the session returns only few fields that does not include userId of the user from the database.

I created however a function that I intend to use with every getServerSideProps request. The function returns the following:

{
  user: {
    name: 'daniel sas',
    email: 'emailofuser@gmail.com',
    image: 'https://lh3.gooleusercontent.com/a/AEdFTp6r44ZwqcfJORNnuYtbVv_LYbab-wv5Uyxk=s96-c',
    userId: 'clbcpc0hi0002sb1wsiea3q5d'
  },
  expires: '2022-12-17T20:18:52.580Z'
}

The problem is I am getting an error that does not allow me to pass the props in the page:

Error: Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?

In the function I get the user by the email, and attach the userId.

import { getSession } from "next-auth/react";
import prisma from './prisma'

// This function get the email and returns a new session object that includes
//  the userId

export const requireAuthentication = async context => {
    const session = await getSession(context);

    const errorOrUserNotFound = () => {
      return {
        redirect: {
          destination: '/signup',
          permanent: false
        }
      }
    }

    // If there is no user or there is an error ret to signup page
    if (!session) {
        errorOrUserNotFound();
    }

    // If the user is not found return same redirect to signup
    else {
        try {
            const user = await prisma.user.findUnique({where: { email: session.user.email }});

            if (!user) return errorOrUserNotFound();

            // Must return a new session here that contains the userId...
            else {
              const newSession = {
                user: {
                  ...session.user,
                  userId: user.id
                },

                expires: session.expires
              };

              console.log(newSession);

              return {
                props: {
                  session: newSession
                }
              }
            }
        }
        catch (error) {
            if (error) {
              console.log(error);
            }
        }
    }
}

The react component looks like this. In the getServerSideProps i return the await function. The problem is that when I log the prop in the serverside, I get the following:

{
  props: { session: { user: [Object], expires: '2022-12-17T20:18:52.580Z' } }
}

However, if i log the props in the clientside, I get an empty object...

//Clientside compoen
import { getSession } from "next-auth/react"
import { Fragment, useState } from "react";
import { requireAuthentication } from "../../lib/requireAuthentication";
import CreateListModal from "./CreateListModal";

const DashboardPage = props => {

  const [loading, setloading] = useState(false);

  console.log(props);

  return (

      <CreateListModal userId={props.userId} loading={loading} setloading={setloading} />

  )
}

export const getServerSideProps = async context => {
  const session = await getSession(context);

  const reqAuth = await requireAuthentication(context);
  console.log(reqAuth);

  return reqAuth
}

export default DashboardPage;


问:
No sound after running engine.runandWait()
I am trying to work with the pyttx3 library and I am trying to output speech by supplying a text to engine.say('My text'), then I run the engine.runandwait() function but the program just stays there and does nothing.

Here is my code:

import pyttsx3

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
speak("Best")
```


问:
Flutter push notifications big picture on iOS
I am using awesome_notifications in Flutter to create local push notifications like this as an example:

```<code>await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 12345,
        channelKey: channelKey,
        title: title,
        body: body,
        bigPicture: "asset://assets/images/example.jpeg",
        notificationLayout: NotificationLayout.BigPicture,
      ),
      schedule: NotificationCalendar.fromDate(
        date: DateTime.now().add(Duration(seconds: 1)),
      ),
    );
</code>```

On Android, I get a nice notification with a big picture. On iOS though, I just get this. Does anyone know how to get a big picture notification on iOS?

Body:
I am using awesome_notifications in Flutter to create local push notifications like this as an example:

await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 12345,
        channelKey: channelKey,
        title: title,
        body: body,
        bigPicture: "asset://assets/images/example.jpeg",
        notificationLayout: NotificationLayout.BigPicture,
      ),
      schedule: NotificationCalendar.fromDate(
        date: DateTime.now().add(Duration(seconds: 1)),
      ),
    );

On Android, I get a nice notification with a big picture. On iOS though, I just get this. Does anyone know how to get a big picture notification on iOS?


问:
Problem with azure web app FASTAPI - AttributeError: 'PosixPath' object has no attribute 'expanduser'
I am trying to deploy Python FastApi on Azure webapp .
Deployment is working as expected .

But after deployment Azure webapp is showing error . Error is only appearing in Azure Webapp

```<code>/home/LogFiles/2022_12_17_lw1sdlwk0006KE_default_docker.log  (https://example.scm.azurewebsites.net/api/vfs/LogFiles/2022_12_17_lw1sdlwk0006KE_default_docker.log)
2022-12-17T18:09:53.379366634Z     from app.core.log_file_handler import logs as Log
2022-12-17T18:09:53.379535236Z   File "/tmp/8dae0581e110892/app/core/log_file_handler.py", line 5, in <module>
2022-12-17T18:09:53.379544536Z     from app.core.utils import settings
2022-12-17T18:09:53.379548236Z   File "/tmp/8dae0581e110892/app/core/utils.py", line 154, in <module>
2022-12-17T18:09:53.379551936Z     settings = Settings()
2022-12-17T18:09:53.388338451Z   File "pydantic/env_settings.py", line 39, in pydantic.env_settings.BaseSettings.__init__
2022-12-17T18:09:53.388357051Z   File "pydantic/env_settings.py", line 73, in pydantic.env_settings.BaseSettings._build_values
2022-12-17T18:09:53.388362051Z   File "pydantic/env_settings.py", line 166, in pydantic.env_settings.EnvSettingsSource.__call__
2022-12-17T18:09:53.388365951Z AttributeError: 'PosixPath' object has no attribute 'expanduser'
</code>```

Running fine locally on windows , linux , macos , only problem is happening in Azure web app
This is my utils.py file

load_dotenv()

class Settings(BaseSettings):
    """
    Get credentials values from .env file
    """

    # Environment
    environment: str = os.environ.get("ENVIRONMENT")

    # Database credentials
    db_username: str = os.environ.get("DB_USERNAME")
    db_password: str = os.environ.get("DB_PASSWORD")
    db_url: str = os.environ.get("DB_URL")
    db_name: str = os.environ.get("DB_NAME")

    title: str = "GTCRM-API"
    description: str = """ API  """
    version: str = "1.3.0"
    contact = {
        "name": "Appname",
        "url": "https://example.com/",
        "email": "support@example.com",
    }
    openapi_tags = tags_metadata
    docs_url: str = "/docs"
    redoc_url: str = "/redocs"
    openapi_url: str = "/openapi.json"
    disable_docs: bool = os.environ.get("ENVIRONMENT") != "development"

    @property
    def fastapi_kwargs(self) -> Dict[str, Any]:
        """This returns a dictionary of the most commonly used keyword
        arguments when initializing a FastAPI instance.

        If `self.disable_docs` is True, the various docs-related arguments
        are disabled, preventing spec from being published.
        """
        fastapi_kwargs: Dict[str, Any] = {
            "title": self.title,
            "description": self.description,
            "version": self.version,
            "contact": self.contact,
            "openapi_tags": self.openapi_tags,
            "docs_url": self.docs_url,
            "redoc_url": self.redoc_url,
            "openapi_url": self.openapi_url,
        }
        if self.disable_docs:
            fastapi_kwargs.update(
                {"docs_url": None, "openapi_url": None, "redoc_url": None}
            )
        return fastapi_kwargs

    class Config:
        env_file = ".env"

# create instance of class
settings = Settings()

s3_client = boto3.client(
    "s3",
    # some env declatrion is deleted above to keep code short below where listed
    aws_access_key_id=settings.aws_access_key_id,
    aws_secret_access_key=settings.aws_secret_access_key,
    region_name=settings.region_name,
)
```

I am not able to understand what i doing error

Body:
I am trying to deploy Python FastApi on Azure webapp .
Deployment is working as expected .

But after deployment Azure webapp is showing error . Error is only appearing in Azure Webapp

/home/LogFiles/2022_12_17_lw1sdlwk0006KE_default_docker.log  (https://example.scm.azurewebsites.net/api/vfs/LogFiles/2022_12_17_lw1sdlwk0006KE_default_docker.log)
2022-12-17T18:09:53.379366634Z     from app.core.log_file_handler import logs as Log
2022-12-17T18:09:53.379535236Z   File "/tmp/8dae0581e110892/app/core/log_file_handler.py", line 5, in <module>
2022-12-17T18:09:53.379544536Z     from app.core.utils import settings
2022-12-17T18:09:53.379548236Z   File "/tmp/8dae0581e110892/app/core/utils.py", line 154, in <module>
2022-12-17T18:09:53.379551936Z     settings = Settings()
2022-12-17T18:09:53.388338451Z   File "pydantic/env_settings.py", line 39, in pydantic.env_settings.BaseSettings.__init__
2022-12-17T18:09:53.388357051Z   File "pydantic/env_settings.py", line 73, in pydantic.env_settings.BaseSettings._build_values
2022-12-17T18:09:53.388362051Z   File "pydantic/env_settings.py", line 166, in pydantic.env_settings.EnvSettingsSource.__call__
2022-12-17T18:09:53.388365951Z AttributeError: 'PosixPath' object has no attribute 'expanduser'

Running fine locally on windows , linux , macos , only problem is happening in Azure web app
This is my utils.py file

load_dotenv()

class Settings(BaseSettings):
    """
    Get credentials values from .env file
    """

    # Environment
    environment: str = os.environ.get("ENVIRONMENT")

    # Database credentials
    db_username: str = os.environ.get("DB_USERNAME")
    db_password: str = os.environ.get("DB_PASSWORD")
    db_url: str = os.environ.get("DB_URL")
    db_name: str = os.environ.get("DB_NAME")

    title: str = "GTCRM-API"
    description: str = """ API  """
    version: str = "1.3.0"
    contact = {
        "name": "Appname",
        "url": "https://example.com/",
        "email": "support@example.com",
    }
    openapi_tags = tags_metadata
    docs_url: str = "/docs"
    redoc_url: str = "/redocs"
    openapi_url: str = "/openapi.json"
    disable_docs: bool = os.environ.get("ENVIRONMENT") != "development"

    @property
    def fastapi_kwargs(self) -> Dict[str, Any]:
        """This returns a dictionary of the most commonly used keyword
        arguments when initializing a FastAPI instance.

        If `self.disable_docs` is True, the various docs-related arguments
        are disabled, preventing spec from being published.
        """
        fastapi_kwargs: Dict[str, Any] = {
            "title": self.title,
            "description": self.description,
            "version": self.version,
            "contact": self.contact,
            "openapi_tags": self.openapi_tags,
            "docs_url": self.docs_url,
            "redoc_url": self.redoc_url,
            "openapi_url": self.openapi_url,
        }
        if self.disable_docs:
            fastapi_kwargs.update(
                {"docs_url": None, "openapi_url": None, "redoc_url": None}
            )
        return fastapi_kwargs

    class Config:
        env_file = ".env"

# create instance of class
settings = Settings()

s3_client = boto3.client(
    "s3",
    # some env declatrion is deleted above to keep code short below where listed
    aws_access_key_id=settings.aws_access_key_id,
    aws_secret_access_key=settings.aws_secret_access_key,
    region_name=settings.region_name,
)

I am not able to understand what i doing error


问:
How do I create a stickied message in Discord.js
I've looked all over and I can't find a solution.

I'm using discord js using non-slash commands.

How could I make it so you have a message from the bot and if someone types in the channel the bot's message will get deleted and resent

I want to do this in a sense of a server request channel so you need to add the channel you want the command to run and what you want it to say:

e.g:

Stickied Message

Name:
Request Needed:
Approved By:

how could I program that? Thanks :) <3

I ahve googled online and can't see anything relating to this topic - maybe I'm not searching the right things?

Tried Discord.js V13 | Sticky Message but did not work


问:
Media files showing 504 error on resource fetch on chrome
On chrome (tried many devices)

My (Angular) web app is sitting on a subdomain and referencing media in a folder in the main domain using https. When using http to access the web app, all media referenced load well but when using https to access the web app, the media don't load and on inspection, media fetch are showing 504 error.

But on Firefox, everything is fine.

Please what could be wrong? Could be the .htaccess configuration or something?

Chrome Developer Tool (Network Tab)
enter image description here

My .htaccess file
`

```<code>RewriteEngine on
<FilesMatch "\.(mp4)$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
        Header set Access-Control-Max-Age "3600"
    </IfModule>
</FilesMatch>

# RewriteCond %{HTTPS} !on
# RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ /index.html [L,QSA]
</IfModule>
# RewriteRule ^.*$ /index.php [L,QSA]

#for passing HTTP AUTHORIZATION header
CGIPassAuth On

# BEGIN cPanel-generated php ini directives, do not edit
# Manual editing of this file may result in unexpected behavior.
# To make changes to this file, use the cPanel MultiPHP INI Editor (Home >> Software >> MultiPHP INI Editor)
# For more information, read our documentation (https://go.cpanel.net/EA4ModifyINI)
<IfModule php7_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 128M
   php_value post_max_size 120M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php73"
   php_value upload_max_filesize 120M
   php_flag zlib.output_compression On
</IfModule>
<IfModule lsapi_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 128M
   php_value post_max_size 120M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php73"
   php_value upload_max_filesize 120M
   php_flag zlib.output_compression On
</IfModule>
# END cPanel-generated php ini directives, do not edit

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php80” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php80___lsphp .php .php8 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

</code>```

`

I have searched the internet for solution but clear cut answer

Body:
On chrome (tried many devices)

My (Angular) web app is sitting on a subdomain and referencing media in a folder in the main domain using https. When using http to access the web app, all media referenced load well but when using https to access the web app, the media don't load and on inspection, media fetch are showing 504 error.

But on Firefox, everything is fine.

Please what could be wrong? Could be the .htaccess configuration or something?

Chrome Developer Tool (Network Tab)
enter image description here

My .htaccess file
`

RewriteEngine on
<FilesMatch "\.(mp4)$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
        Header set Access-Control-Max-Age "3600"
    </IfModule>
</FilesMatch>

# RewriteCond %{HTTPS} !on
# RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ /index.html [L,QSA]
</IfModule>
# RewriteRule ^.*$ /index.php [L,QSA]

#for passing HTTP AUTHORIZATION header
CGIPassAuth On

# BEGIN cPanel-generated php ini directives, do not edit
# Manual editing of this file may result in unexpected behavior.
# To make changes to this file, use the cPanel MultiPHP INI Editor (Home >> Software >> MultiPHP INI Editor)
# For more information, read our documentation (https://go.cpanel.net/EA4ModifyINI)
<IfModule php7_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 128M
   php_value post_max_size 120M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php73"
   php_value upload_max_filesize 120M
   php_flag zlib.output_compression On
</IfModule>
<IfModule lsapi_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 128M
   php_value post_max_size 120M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php73"
   php_value upload_max_filesize 120M
   php_flag zlib.output_compression On
</IfModule>
# END cPanel-generated php ini directives, do not edit

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php80” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php80___lsphp .php .php8 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

`

I have searched the internet for solution but clear cut answer


问:
What is causing this TypeError when trying to insert data into a Postgres DB via a Lambda Function?
I'm using node 16.17.0, the default lambda aws-sdk for Nodejs, and "pg": "^8.7.3".

After using the s3.getObject(params).promise(), I'm able to store the contents of a JSON file (in the screenshot), and from there, I have a SQL statement to insert the retrieved data into the confirmed correct columns within the database (I've used dummmy data before to insert 5000 rows). However, with the following code, I'm getting a type error as shown in the description. I have absolutely no idea how to solve this "promise" issue. I've tried creating my own promise and using a .then() to insert data to no avail. I'm wondering could this be a versioning issue more than anything? This is the only get-object method that works in my environment. I've gotten the getObject(params, (err, data)) method to work on my personal machine a few times, but that solution simply won't work in this case. I've tried googling the solution and I'm not finding anyone who has seen this error

JSON data structure

Every variation of creating a new Promise manually ends up with this error. Also, that JSON.stringify was only to see if maybe the data wasn't in string format, but neither keeping nor removing that parsing works.

```<code>

const insertLegacyData = async (event, _context, _callback) => {
    const queries = require("../Utility/queries");
    const helper = require("../Utility/helper");
    const AWS = require('aws-sdk');
    const s3 = new AWS.S3();
    const { Pool } = require("pg");
    try {

        var params = {
            Bucket: "bucketName",
            Key: "theData.json"
        };

        var results = await s3.getObject(params).promise();
        results = JSON.parse(results.Body).results[0]['items'];
        results = JSON.stringify(results.results[0]['items']);

        let token = helper.getToken();
        var pool = new Pool(helper.getPool(token));

        pool.query('TRUNCATE TABLE "fumes_schema"."consumption"', (err, res) => {
            if (err) throw err;
        });

        for (let i = 0; i < 5923; i++) {
            console.log(`Iteration: ${i}`);
            pool.query('INSERT INTO "schema"."theTable"(seq_nbr, origination, destination, aircraft_type, month_12_gallons, month_12_flights, month_12_minutes, month_11_gallons, month_11_flights, month_11_minutes, month_10_gallons, month_10_flights, month_10_minutes, month_09_gallons, month_09_flights, month_09_minutes, month_08_gallons, month_08_flights, month_08_minutes, month_07_gallons, month_07_flights, month_07_minutes, month_06_gallons, month_06_flights, month_06_minutes, month_05_gallons, month_05_flights, month_05_minutes, month_04_gallons, month_04_flights, month_04_minutes, month_03_gallons, month_03_flights, month_03_minutes, month_02_gallons, month_02_flights, month_02_minutes, month_01_gallons, month_01_flights, month_01_minutes) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40);', [(i + 1), [results[i]["depature_arpt_cd"], results[i]["arr_arpt_cd"], results[i]["ac_typ_cd"], results[i]["m12gal"], results[i]["m12cnt"], results[i]["m12_duration_in_minutes"], results[i]["m11gal"], results[i]["m11cnt"], results[i]["m11_duration_in_minutes"], results[i]["m10gal"], results[i]["m10cnt"], results[i]["m10_duration_in_minutes"], results[i]["m9gal"], results[i]["m9cnt"], results[i]["m9_duration_in_minutes"], results[i]["m8gal"], results[i]["m8cnt"], results[i]["m8_duration_in_minutes"], results[i]["m7gal"], results[i]["m7cnt"], results[i]["m7_duration_in_minutes"], results[i]["m6gal"], results[i]["m6cnt"], results[i]["m6_duration_in_minutes"], results[i]["m5gal"], results[i]["m5cnt"], results[i]["m5_duration_in_minutes"], results[i]["m4gal"], results[i]["m4cnt"], results[i]["m4_duration_in_minutes"], results[i]["m3gal"], results[i]["m3cnt"], results[i]["m3_duration_in_minutes"], results[i]["m2gal"], results[i]["m2cnt"], results[i]["m2_duration_in_minutes"], results[i]["m1gal"], results[i]["m1cnt"], results[i]["m1_duration_in_minutes"]]]);
        };

        await pool.end();

        response = helper.createSuccessResponse('Successful DB truncation & legacy data insertion', 'legacyData', 'Legacy Data Insertion', {});
        return {
            statusCode: 200,
            body: JSON.stringify(response)
        };
    } catch (err) {
        response = helper.createErrorResponse(`${err}`, 'legacyData', 'Legacy Data Insertion', {});
        return {
            statusCode: 500,
            body: JSON.stringify(response)
        };
    }
};
</code>```
```<code>{
    "errorType": "TypeError",
    "errorMessage": "The \"string\" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of Promise",
    "code": "ERR_INVALID_ARG_TYPE",
    "stack": [
        "TypeError [ERR_INVALID_ARG_TYPE]: The \"string\" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of Promise",
        "    at new NodeError (node:internal/errors:372:5)",
        "    at Function.byteLength (node:buffer:735:11)",
        "    at Writer.addCString (/var/task/node_modules/pg-protocol/dist/buffer-writer.js:42:30)",
        "    at Object.password (/var/task/node_modules/pg-protocol/dist/serializer.js:25:19)",
        "    at Connection.password (/var/task/node_modules/pg/lib/connection.js:131:26)",
        "    at /var/task/node_modules/pg/lib/client.js:238:23",
        "    at Client._checkPgPass (/var/task/node_modules/pg/lib/client.js:225:7)",
        "    at Client._handleAuthCleartextPassword (/var/task/node_modules/pg/lib/client.js:237:10)",
        "    at Connection.emit (node:events:527:28)",
        "    at Connection.emit (node:domain:475:12)"
    ]
}
</code>```

EDIT: The getToken and getPool code:

const getToken = async () => {
    const signer = new AWS.RDS.Signer({
        region: process.env.AWS_REGION ? process.env.AWS_REGION : '',
        hostname: process.env.Fumes_RDS_HOST ? process.env.Fumes_RDS_HOST : '',
        port: Number(process.env.Fumes_RDS_PORT),
        username: process.env.Fumes_RDS_USER ? process.env.Fumes_RDS_USER : ''
    });
    return await signer.getAuthToken({ username: process.env.Fumes_RDS_USER ? process.env.Fumes_RDS_USER : '' });
}

function getPool(token) {
    return {
        user: process.env.Fumes_RDS_USER ? process.env.Fumes_RDS_USER : '',
        host: process.env.Fumes_RDS_HOST ? process.env.Fumes_RDS_HOST : '',
        database: process.env.Fumes_RDS_DB ? process.env.Fumes_RDS_DB : '',
        password: token,
        port: Number(process.env.Fumes_RDS_PORT),
        ssl: { rejectUnauthorized: false },
        /* eslint-disable */
        authSwitchHandler: function ({ _pluginName, _pluginData }, _cb) {
            /* eslint-enable */
        }
    }
}```

Body:
I'm using node 16.17.0, the default lambda aws-sdk for Nodejs, and "pg": "^8.7.3".

After using the s3.getObject(params).promise(), I'm able to store the contents of a JSON file (in the screenshot), and from there, I have a SQL statement to insert the retrieved data into the confirmed correct columns within the database (I've used dummmy data before to insert 5000 rows). However, with the following code, I'm getting a type error as shown in the description. I have absolutely no idea how to solve this "promise" issue. I've tried creating my own promise and using a .then() to insert data to no avail. I'm wondering could this be a versioning issue more than anything? This is the only get-object method that works in my environment. I've gotten the getObject(params, (err, data)) method to work on my personal machine a few times, but that solution simply won't work in this case. I've tried googling the solution and I'm not finding anyone who has seen this error

JSON data structure

Every variation of creating a new Promise manually ends up with this error. Also, that JSON.stringify was only to see if maybe the data wasn't in string format, but neither keeping nor removing that parsing works.

const insertLegacyData = async (event, _context, _callback) => {
    const queries = require("../Utility/queries");
    const helper = require("../Utility/helper");
    const AWS = require('aws-sdk');
    const s3 = new AWS.S3();
    const { Pool } = require("pg");
    try {

        var params = {
            Bucket: "bucketName",
            Key: "theData.json"
        };

        var results = await s3.getObject(params).promise();
        results = JSON.parse(results.Body).results[0]['items'];
        results = JSON.stringify(results.results[0]['items']);

        let token = helper.getToken();
        var pool = new Pool(helper.getPool(token));

        pool.query('TRUNCATE TABLE "fumes_schema"."consumption"', (err, res) => {
            if (err) throw err;
        });

        for (let i = 0; i < 5923; i++) {
            console.log(`Iteration: ${i}`);
            pool.query('INSERT INTO "schema"."theTable"(seq_nbr, origination, destination, aircraft_type, month_12_gallons, month_12_flights, month_12_minutes, month_11_gallons, month_11_flights, month_11_minutes, month_10_gallons, month_10_flights, month_10_minutes, month_09_gallons, month_09_flights, month_09_minutes, month_08_gallons, month_08_flights, month_08_minutes, month_07_gallons, month_07_flights, month_07_minutes, month_06_gallons, month_06_flights, month_06_minutes, month_05_gallons, month_05_flights, month_05_minutes, month_04_gallons, month_04_flights, month_04_minutes, month_03_gallons, month_03_flights, month_03_minutes, month_02_gallons, month_02_flights, month_02_minutes, month_01_gallons, month_01_flights, month_01_minutes) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40);', [(i + 1), [results[i]["depature_arpt_cd"], results[i]["arr_arpt_cd"], results[i]["ac_typ_cd"], results[i]["m12gal"], results[i]["m12cnt"], results[i]["m12_duration_in_minutes"], results[i]["m11gal"], results[i]["m11cnt"], results[i]["m11_duration_in_minutes"], results[i]["m10gal"], results[i]["m10cnt"], results[i]["m10_duration_in_minutes"], results[i]["m9gal"], results[i]["m9cnt"], results[i]["m9_duration_in_minutes"], results[i]["m8gal"], results[i]["m8cnt"], results[i]["m8_duration_in_minutes"], results[i]["m7gal"], results[i]["m7cnt"], results[i]["m7_duration_in_minutes"], results[i]["m6gal"], results[i]["m6cnt"], results[i]["m6_duration_in_minutes"], results[i]["m5gal"], results[i]["m5cnt"], results[i]["m5_duration_in_minutes"], results[i]["m4gal"], results[i]["m4cnt"], results[i]["m4_duration_in_minutes"], results[i]["m3gal"], results[i]["m3cnt"], results[i]["m3_duration_in_minutes"], results[i]["m2gal"], results[i]["m2cnt"], results[i]["m2_duration_in_minutes"], results[i]["m1gal"], results[i]["m1cnt"], results[i]["m1_duration_in_minutes"]]]);
        };

        await pool.end();

        response = helper.createSuccessResponse('Successful DB truncation & legacy data insertion', 'legacyData', 'Legacy Data Insertion', {});
        return {
            statusCode: 200,
            body: JSON.stringify(response)
        };
    } catch (err) {
        response = helper.createErrorResponse(`${err}`, 'legacyData', 'Legacy Data Insertion', {});
        return {
            statusCode: 500,
            body: JSON.stringify(response)
        };
    }
};

{
    "errorType": "TypeError",
    "errorMessage": "The \"string\" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of Promise",
    "code": "ERR_INVALID_ARG_TYPE",
    "stack": [
        "TypeError [ERR_INVALID_ARG_TYPE]: The \"string\" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of Promise",
        "    at new NodeError (node:internal/errors:372:5)",
        "    at Function.byteLength (node:buffer:735:11)",
        "    at Writer.addCString (/var/task/node_modules/pg-protocol/dist/buffer-writer.js:42:30)",
        "    at Object.password (/var/task/node_modules/pg-protocol/dist/serializer.js:25:19)",
        "    at Connection.password (/var/task/node_modules/pg/lib/connection.js:131:26)",
        "    at /var/task/node_modules/pg/lib/client.js:238:23",
        "    at Client._checkPgPass (/var/task/node_modules/pg/lib/client.js:225:7)",
        "    at Client._handleAuthCleartextPassword (/var/task/node_modules/pg/lib/client.js:237:10)",
        "    at Connection.emit (node:events:527:28)",
        "    at Connection.emit (node:domain:475:12)"
    ]
}

EDIT: The getToken and getPool code:

const getToken = async () => {
    const signer = new AWS.RDS.Signer({
        region: process.env.AWS_REGION ? process.env.AWS_REGION : '',
        hostname: process.env.Fumes_RDS_HOST ? process.env.Fumes_RDS_HOST : '',
        port: Number(process.env.Fumes_RDS_PORT),
        username: process.env.Fumes_RDS_USER ? process.env.Fumes_RDS_USER : ''
    });
    return await signer.getAuthToken({ username: process.env.Fumes_RDS_USER ? process.env.Fumes_RDS_USER : '' });
}

function getPool(token) {
    return {
        user: process.env.Fumes_RDS_USER ? process.env.Fumes_RDS_USER : '',
        host: process.env.Fumes_RDS_HOST ? process.env.Fumes_RDS_HOST : '',
        database: process.env.Fumes_RDS_DB ? process.env.Fumes_RDS_DB : '',
        password: token,
        port: Number(process.env.Fumes_RDS_PORT),
        ssl: { rejectUnauthorized: false },
        /* eslint-disable */
        authSwitchHandler: function ({ _pluginName, _pluginData }, _cb) {
            /* eslint-enable */
        }
    }
}