Skip to content
This repository was archived by the owner on May 20, 2025. It is now read-only.

Commit 443693f

Browse files
raksivHomelessDinosaurdavemooreuwsjyecusch
authored
docs: add postgres-db guide (#719)
Co-authored-by: Ryan Cartwright <[email protected]> Co-authored-by: David Moore <[email protected]> Co-authored-by: Jye Cusch <[email protected]>
1 parent 71d3ef9 commit 443693f

File tree

6 files changed

+206
-0
lines changed

6 files changed

+206
-0
lines changed
Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
---
2+
description: 'How to work with Nitric SQL Databases using PostgreSQL'
3+
tags:
4+
- Databases & CMS
5+
languages:
6+
- typescript
7+
- javascript
8+
published_at: 2025-04-03
9+
---
10+
11+
# Nitric SQL Databases with PostgreSQL
12+
13+
This guide demonstrates how to use PostgreSQL with Nitric's [SQL database](/sql) feature. We will be creating a simple to-do app. The finished source can be found [here](https://github.com/nitrictech/examples/tree/main/v1/nitric-pgsql).
14+
15+
<Note>SQL databases are currently in preview and only support PostgreSQL.</Note>
16+
17+
## Create a new Nitric project
18+
19+
The first step is to create a new Nitric TypeScript project using the [Nitric CLI](/reference/cli).
20+
21+
```bash
22+
nitric new todo-app ts-starter
23+
```
24+
25+
## Enabling SQL databases
26+
27+
SQL databases are currently in Preview. To enable this feature in your project, add the following to your `nitric.yaml` file:
28+
29+
```yaml title: nitric.yaml
30+
preview:
31+
- sql-databases
32+
```
33+
34+
## Add a PostgreSQL client
35+
36+
In this guide, we'll use the [node-postgres](https://github.com/brianc/node-postgres) library, but feel free to use another client of your choice and adjust the steps accordingly.
37+
38+
```bash
39+
npm install pg
40+
```
41+
42+
## Create a Nitric SQL Database and Connect to it
43+
44+
Use Nitric’s `sql` feature to create a new SQL database, then use `.connectionString()` and the `pg` library to connect to it.
45+
46+
```ts title: resources/db.ts
47+
import { sql } from '@nitric/sdk'
48+
import { Client } from 'pg'
49+
50+
const db = sql('todo-db', {
51+
migrations: 'file://migrations/todos',
52+
})
53+
54+
let client: Client
55+
56+
const getClient = async () => {
57+
if (!client) {
58+
const connectionString = await db.connectionString()
59+
client = new Client({ connectionString })
60+
await client.connect()
61+
}
62+
return client
63+
}
64+
65+
export default getClient
66+
```
67+
68+
## Database Migrations
69+
70+
Create a migration file to define the `todos` table.
71+
72+
```sql title: migrations/todos/1_create_table.up.sql
73+
CREATE TABLE IF NOT EXISTS todos (
74+
id SERIAL PRIMARY KEY,
75+
content TEXT NOT NULL,
76+
done BOOLEAN DEFAULT FALSE
77+
);
78+
```
79+
80+
## Developing the API
81+
82+
### Building the API
83+
84+
Delete the `services/hello.ts` file and create a new one called `todos.ts`, which will contain our API endpoints.
85+
86+
```ts title: services/todos.ts
87+
import { api } from '@nitric/sdk'
88+
import getClient from '../resources/db'
89+
90+
const mainApi = api('main')
91+
92+
// Fetch all todos
93+
mainApi.get('/todos', async (ctx) => {
94+
const client = await getClient()
95+
const result = await client.query('SELECT * FROM todos ORDER BY id ASC')
96+
return ctx.res.json(result.rows)
97+
})
98+
99+
// Insert a new todo
100+
mainApi.post('/todos/', async (ctx) => {
101+
const { content } = ctx.req.json()
102+
const client = await getClient()
103+
await client.query('INSERT INTO todos (content, done) VALUES ($1, $2)', [
104+
content,
105+
false,
106+
])
107+
})
108+
109+
// Update content of a todo
110+
mainApi.patch('/todos/:id', async (ctx) => {
111+
const { id } = ctx.req.params
112+
const { content } = ctx.req.json()
113+
const client = await getClient()
114+
await client.query('UPDATE todos SET content = $1 WHERE id = $2', [
115+
content,
116+
parseInt(id),
117+
])
118+
})
119+
120+
// Toggle todo completion status
121+
mainApi.patch('/todos/:id/toggle', async (ctx) => {
122+
const { id } = ctx.req.params
123+
const client = await getClient()
124+
125+
await client.query('UPDATE todos SET done = NOT done WHERE id = $1', [
126+
parseInt(id),
127+
])
128+
})
129+
130+
// Delete a todo
131+
mainApi.delete('/todos/:id', async (ctx) => {
132+
const { id } = ctx.req.params
133+
const client = await getClient()
134+
await client.query('DELETE FROM todos WHERE id = $1', [parseInt(id)])
135+
})
136+
```
137+
138+
### Start testing with `nitric start`
139+
140+
Run `nitric start` to start your local database and APIs.
141+
142+
```bash
143+
nitric start
144+
```
145+
146+
Using the dashboard, apply your migrations from the databases tab to initialize your local db.
147+
148+
![Apply migrations](/docs/images/guides/nitric-and-pgsql/step-1.png)
149+
150+
### Add some todos using the Nitric dashboard
151+
152+
Open the local dashboard at <a target="_blank" href="http://localhost:49152">localhost:49152</a>, then navigate to the `POST /todos` endpoint and add some content to the body of the request, stating the `content` key and value of the todo task and click send.
153+
154+
![Add text content for the todo](/docs/images/guides/nitric-and-pgsql/step-2.png)
155+
156+
Let's check our todo got created by calling the `GET /todos` endpoint, which will list all todos.
157+
158+
![Check that our todo get created](/docs/images/guides/nitric-and-pgsql/step-3.png)
159+
160+
Let's toggle our todo as done, navigate to the `PATCH /todos/{id}/toggle` and enter the correct `id` to toggle.
161+
162+
![Toggle our todo as done](/docs/images/guides/nitric-and-pgsql/step-4.png)
163+
164+
Finally, let's check our todo got toggled to done by calling the `GET /todos` endpoint.
165+
166+
![View the todo change](/docs/images/guides/nitric-and-pgsql/step-5.png)
167+
168+
Feel free to test the other endpoints to update or delete the todo items.
169+
170+
## Deploying to AWS
171+
172+
### Create your stack
173+
174+
Create an AWS stack called `aws-staging` for your staging environment.
175+
176+
```bash
177+
nitric stack new aws-staging aws
178+
```
179+
180+
Inside the stack file, ensure you set your `region`.
181+
182+
```yaml title:nitric.dev.yaml
183+
provider: nitric/aws@latest
184+
region: us-east-2
185+
```
186+
187+
### Deploy
188+
189+
Deploy to AWS using the `nitric up` command. Ensure you have set up your [AWS credentials](/providers/pulumi/aws#usage) correctly.
190+
191+
```bash
192+
nitric up
193+
```
194+
195+
### Tear down
196+
197+
To avoid unwanted costs of running your test app, you can tear down the stack using the `nitric down` command.
198+
199+
```bash
200+
nitric down
201+
```
202+
203+
### Prefer to use an ORM? We also have these guides:
204+
205+
- [Nitric SQL with Drizzle](./nitric-and-drizzle).
206+
- [Nitric SQL with Prisma](./nitric-and-prisma).
107 KB
Loading
132 KB
Loading
143 KB
Loading
137 KB
Loading
139 KB
Loading

0 commit comments

Comments
 (0)