CodeGenieApp / CodeGenieApp/serverless-express

How to use Async/await?

Offen
#546 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
JavaScript
Sterne
5.3k
Forks
674
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

I read https://github.com/vendia/serverless-express/issues/481 https://github.com/vendia/serverless-express/issues/134 and https://github.com/vendia/serverless-express/blob/mainline/examples/basic-starter-api-gateway-v2/src/lambda-async-setup.js but I still cannot figure out how to connect to a database (postgres, not from RDS). A minimal example of what I'm trying to do:

```
//lambda.js
require('source-map-support/register')
const serverlessExpress = require('@vendia/serverless-express')
const app = require('./app')

exports.handler = serverlessExpress({ app })

//app.js
require('dotenv').config();
const { Client } = require('pg') //leaving out the rest of the libraries
router.post('/createUser', async function (req, res) {
await sqlRequest(`INSERT INTO users ("name", "age" "ect..") VALUES ( ${req.body.name}, ${req.body.age}, ${req.body.ect..})`);
res.status(200).send("inserted!");
})
router.post('/getUser', async function (req, res, next) {
let result = sqlRequest('SELECT * FROM users WHERE id = ' + req.body.id) //all user input is escaped in full version
res.status(200).json(result);
})

async function sqlRequest(sql, params){
const client = new Client(process.env.DATABASE_URL); //this is a postgres URL
await client.connect();
let result = await client.query(sql);
client.end();
return result.rows;
}
module.exports = app
```

The full app is a few hundred lines with many more queries and works fine locally. I believe the issue is being caused by async/await. Is there any way to do this in lambda? If this isn't the right library to use, can someone point me in the right direction? Would you recommend I switch to Azure or some other service to make it easier? Any advice on how to proceed is appreciated.

Beitragsleitfaden

Beitragsleitfaden öffnen

Rechercherichtung

Beginne mit examples/basic-starter-api-gateway-v2/src/lambda-async-setup.js und vergleiche es mit den lambda.js- und app.js-Codeausschnitten im Issue. Ermittle, ob das Repository ein minimales PostgreSQL-Verbindungsbeispiel für asynchrone Express-Handler dokumentieren sollte, und definiere „fertig“ als ein klares, funktionierendes Beispiel, das erklärt, wie die Datenbankabfragen in das Lambda-Setup passen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
aws, express, javascript, node.js, postgresql
Bereich
api, backend, cloud, databases
Issue-Typ
Dokumentation
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.