Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Postgres #1766

Merged
merged 10 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions .eslintrc

This file was deleted.

16 changes: 16 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"extends": ["@codeyourfuture/standard", "prettier"],
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module"
},
"plugins": ["import"],
"reportUnusedDisableDirectives": true,
"root": true,
"rules": {
"import/order": [
"error",
{ "alphabetize": { "order": "asc" }, "newlines-between": "always" }
]
}
}
43 changes: 40 additions & 3 deletions .github/workflows/push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ on:
jobs:
nodejs:
runs-on: ubuntu-latest
services:
postgres:
image: postgres
env:
POSTGRES_PASSWORD: keepitsecret
POSTGRES_USER: testdb
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
env:
DATABASE_URL: postgres://testdb:keepitsecret@localhost:5432/testdb
steps:
- uses: textbook/take-action@nodejs
with:
Expand All @@ -22,6 +37,19 @@ jobs:
- run: npm run e2e:dev
docker:
runs-on: ubuntu-latest
services:
postgres:
image: postgres
env:
POSTGRES_PASSWORD: keepitsecret
POSTGRES_USER: testdb
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
steps:
- uses: textbook/take-action@nodejs
with:
Expand All @@ -33,15 +61,24 @@ jobs:
load: true
push: false
tags: textbook/starter-kit:v2
- id: env-file
run: |
echo 'DATABASE_URL=postgres://testdb:keepitsecret@localhost:5432/testdb' >> "$ENV_FILE"
echo 'LOG_LEVEL=debug' >> "$ENV_FILE"
echo 'PORT=4321' >> "$ENV_FILE"
echo 'NODE_ENV=docker' >> "$ENV_FILE"
echo "file=$ENV_FILE" >> "$GITHUB_OUTPUT"
env:
ENV_FILE: docker.env
- id: docker-run
run: |
echo "id=$(docker run \
--detach \
--env LOG_LEVEL=debug \
--env NODE_ENV=docker \
--env-file ${{ steps.env-file.outputs.file }} \
--init \
--publish 4321:80 \
--network 'host' \
textbook/starter-kit:v2)" >> $GITHUB_OUTPUT
- run: npx --yes wait-on --log --timeout 30000 http-get://localhost:4321
- run: npm run e2e
env:
PLAYWRIGHT_BASE_URL: http://localhost:4321
Expand Down
5 changes: 4 additions & 1 deletion api/.eslintrc → api/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"ignorePatterns": ["/static/"],
"overrides": [
{
"files": ["*.test.js"],
"files": ["*.test.js", "setupTests.js"],
"extends": ["plugin:jest/recommended"],
"rules": {
"jest/expect-expect": [
Expand All @@ -14,6 +14,9 @@
}
}
],
"parserOptions": {
"ecmaVersion": 2022
},
"rules": {
"no-console": "warn",
"no-restricted-syntax": [
Expand Down
10 changes: 9 additions & 1 deletion api/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import express from "express";

import db from "./db.js";
import config from "./utils/config.js";
import {
asyncHandler,
clientRouter,
configuredHelmet,
configuredMorgan,
Expand All @@ -20,7 +22,13 @@ if (config.production) {
app.use(httpsOnly());
}

app.get("/healthz", (_, res) => res.sendStatus(200));
app.get(
"/healthz",
asyncHandler(async (_, res) => {
await db.query("SELECT 1;");
res.sendStatus(200);
}),
);

app.use(clientRouter("/api"));

Expand Down
36 changes: 36 additions & 0 deletions api/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { default as pg } from "pg";

import config from "./utils/config.js";
import logger from "./utils/logger.js";

const databaseUrl = new URL(config.databaseUrl);

const localDb = ["0.0.0.0", "127.0.0.1", "localhost"].includes(
databaseUrl.hostname,
);
const sslMode = ["prefer", "require", "verify-ca", "verify-full"].includes(
databaseUrl.searchParams.get("sslmode") ?? "none",
);

const pool = new pg.Pool({
connectionString: databaseUrl.toString(),
connectionTimeoutMillis: 5_000,
ssl: localDb ? false : { rejectUnauthorized: sslMode },
});

pool.on("error", (err) => logger.error("%O", err));

export const connectDb = async () => {
const client = await pool.connect();
logger.info("connected to %s", client.database);
client.release();
};

export const disconnectDb = async () => await pool.end();

export default {
query(...args) {
logger.debug("Postgres query: %O", args);
return pool.query.apply(pool, args);
},
};
1 change: 1 addition & 0 deletions api/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export default {
coverageReporters: [["json", { file: "api.json" }], "text"],
rootDir: ".",
transform: {},
setupFilesAfterEnv: ["<rootDir>/setupTests.js"],
};
1 change: 1 addition & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"express": "^4.18.2",
"helmet": "^7.1.0",
"morgan": "^1.10.0",
"pg": "^8.11.3",
"winston": "^3.11.0"
},
"devDependencies": {
Expand Down
4 changes: 3 additions & 1 deletion api/server.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import app from "./app.js";

import { connectDb } from "./db.js";
import config from "./utils/config.js";
import logger from "./utils/logger.js";

const { port } = config;

await connectDb();

app.listen(port, () => logger.info(`listening on ${port}`));
5 changes: 5 additions & 0 deletions api/setupTests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { connectDb, disconnectDb } from "./db.js";

beforeAll(() => connectDb());

afterAll(() => disconnectDb());
14 changes: 14 additions & 0 deletions api/utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,29 @@ const dotenvPath = resolve(

configDotenv({ path: dotenvPath });

requireArgs(["DATABASE_URL"]);

/**
* @property {URL} databaseUrl
* @property {string} dotenvPath
* @property {string} logLevel
* @property {number} port
* @property {boolean} production
*/
export default {
databaseUrl: process.env.DATABASE_URL,
dotenvPath,
logLevel: process.env.LOG_LEVEL?.toLowerCase() ?? "info",
port: parseInt(process.env.PORT ?? "3000", 10),
production: process.env.NODE_ENV?.toLowerCase() === "production",
};

function requireArgs(required) {
const missing = required.filter((variable) => !process.env[variable]);
if (missing.length > 0) {
process.exitCode = 1;
throw new Error(
`missing required environment variable(s): ${missing.join(", ")}`,
);
}
}
11 changes: 11 additions & 0 deletions api/utils/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ import logger from "./logger.js";

const __dirname = dirname(fileURLToPath(import.meta.url));

export const asyncHandler = (handler) => {
/** @type {import("express").RequestHandler} */
return async (req, res, next) => {
try {
await handler(req, res, next);
} catch (err) {
next(err);
}
};
};

export const clientRouter = (apiRoot) => {
const staticDir = join(__dirname, "..", "static");
const router = Router();
Expand Down
File renamed without changes.
Loading