Quack Service & Controller
We will create our Quack service and controller
Having created the model we can now begin implementing the CRUD functionalities.
We want to list
, create
, read
, update
, and delete
the Quacks.
Quack Service#
We start with the service, so let's go over them one by one. We can start with the imports:
1
import { httpErrors } from "oak";
2
import { AppRouterContext } from "../../main.ts";
3
import { getClient } from "../utils.ts";
4
import { Quack, QuackKeys } from "./model.ts";
List Quacks#
1
export async function listQuack(ctx: AppRouterContext): Promise<Array<Quack>> {
2
const client = await getClient(ctx);
3
4
const result = await client.queryObject<Quack>(
5
`SELECT * FROM ${QuackKeys.TableName}`,
6
);
7
8
client.release();
9
10
return result.rows;
11
}
The list
method is straightforward. With larger applications you would want to
have some filtering, sorting and pagination, but that is a bit outside of the
scope of this course, and is usually handled by ORMs
Create Quack#
1
export async function createQuack(
2
ctx: AppRouterContext,
3
data: Partial<Quack>,
4
): Promise<Quack> {
5
if (!data.text || !data.createdBy) {
6
throw new httpErrors.BadRequest("Missing data");
7
}
8
9
const client = await getClient(ctx);
10
11
const result = await client.queryObject<Quack>({
12
text:
13
`INSERT INTO ${QuackKeys.TableName} (${QuackKeys.ColText}, ${QuackKeys.ColCreatedBy}) VALUES ($1, $2) RETURNING *`,
14
args: [
15
data.text,
16
data.createdBy,
17
],
18
});
19
20
client.release();
21
22
return result.rows[0];
23
}
With a failsafe for missing data, this method creates a Quack with created_by
and text
while using default values for the rest.
Read Quack#
1
export async function readQuack(
2
ctx: AppRouterContext,
3
id: Quack["id"],
4
): Promise<Quack | null> {
5
const client = await getClient(ctx);
6
7
const result = await client.queryObject<Quack>({
8
text:
9
`SELECT * FROM ${QuackKeys.TableName} WHERE ${QuackKeys.ColId} = $1 LIMIT 1`,
10
args: [id],
11
});
12
13
client.release();
14
15
if (result.rows?.[0]?.id !== id) {
16
return null;
17
}
18
19
return result.rows[0];
20
}
Here we simply pass in the id
and return either the Quack
or null