Skip to main content

Express

EmbraceSQL generates an Express Application object suitable for mounting at any location with use into an existing express setup, or run directly with listen.

This server provides full access to AutoCRUD and can be extended with your own SQL.

Requirements

You are going to need:

  • NodeJs >= 18
  • PostgreSQL >= 14

These examples assume you are running locally with your shell able to connect to your PostgreSQL with:

psql

Create a new database dvdrental on your local PostgeSQL server.

curl "https://embracesql.github.io/dvdrental.sql" | psql

Steps

Here is a step by step guide to create an Express server and a fetch client.

Generate an Express Server

Go into a nice blank directory.

npm install @embracesql/express
npm pkg set type=module
mkdir -p ./src
npx embracesqlcli generate express --database postgres://postgres:postgres@localhost/dvdrental > ./src/dvdrental.ts

Notice that this creates a module type for you package.json. This matches the tsconfig.json defaults provided.

Code up an Express Server

We provide handy tsconfig settings that work great with tsx and typescript 5+.

Create two files as shown.

tsconfig.json
{
"extends": "@embracesql/shared/tsconfig/tsconfig.json"
}
./src/express.ts
import { EmbraceSQLExpressApp } from "./dvdrental";

// this is an express application
const app = await EmbraceSQLExpressApp(
"postgres://postgres:postgres@localhost/dvdrental",
);
app.listen(4444);

Test your Express

Start that server:

npx tsx ./src/express.ts

And curl for some data:

curl -X POST http://localhost:4000 \
-H 'Content-Type: application/json' \
-d '{"operation":"Public.Tables.Actor.ByActorId.read","parameters":{"actorId": 1}}'

Generate a Client

It's fun to curl and all, but TypeScript is about types and autocompletion.

Generate a fully typed fetch wrapping client.

npm install @embracesql/client
npx embracesqlcli generate client --database postgres://postgres:postgres@localhost/dvdrental > ./src/dvdrental-browser.ts

Test your Client

Create one file as shown. For fun, try typing it to get a sense of the autocomplete.

./src/client.ts
import { EmbraceSQLClient } from "./dvdrental-browser";

const client = new EmbraceSQLClient({ url: "http://localhost:4444" });

const actor = await client.Public.Tables.Actor.ActorPkey.read({ actorId: 1 });

console.log(actor);

Now run it!

npx tsx ./src/client.ts