This example shows how to connect to a managed PostgreSQL database and perform a query on it.
This example assumes that you are familiar with some products of Scaleway's ecosystem:
- how serverless functions work. If needed, you can check Scaleway official documentation.
- how a managed database for PostgreSQL works, and especially how to create a database and create users with appropriate permissions. Please refer to scaleway's documentation here.
This example uses the Scaleway Serverless Framework Plugin. Please set up your environment with the requirements stated in the Scaleway Serverless Framework Plugin before trying out the example.
Additionnaly it uses the serverless-functions-node library for local testing.
This example shows how to connect to a managed PostgreSQL database and perform a query on it. This example can be extended to adding, deleting, or processing data within a database.
The function connects to a PostgreSQL database and performs an example query on it. This example uses Node 18 runtime. Used packages are specified in package.json.
Create a PostgreSQL database and a user profile with appropriate access permissions.
Fill your secrets within serverless.yml file:
secret:
PG_HOST: "your host IP address"
PG_USER: "your database username"
PG_DATABASE: "your database name"
PG_PASSWORD: "your databse user password"
PG_PORT: "your database port"Once your environment is set up, you can install npm dependencies from package.json file using:
npm installOnce your environment is set up, you can run:
NODE_ENV=test node handler.jsThis will launch a local server, allowing you to test the function. Then, you can run in another terminal:
curl -X GET http://localhost:8080The output should be similar to:
[{"user":"<PG_USER>"}]Finally, if the test succeeded, you can deploy your function with:
serverless deployThen, from the given URL, you can run:
curl -X GET <function URL>When invoking this function, the output should be similar to the one obtained when testing locally.