Skip to content

Commit 7deb59c

Browse files
committed
feat: use PostgreSQL
1 parent bfe0c1b commit 7deb59c

File tree

7 files changed

+127
-4
lines changed

7 files changed

+127
-4
lines changed

.github/workflows/json2db.yml

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
name: json2db
2+
3+
on:
4+
workflow_dispatch:
5+
push:
6+
branches:
7+
- main
8+
9+
jobs:
10+
build:
11+
runs-on: ubuntu-latest
12+
concurrency:
13+
group: ${{ github.workflow }}-${{ github.ref }}
14+
steps:
15+
- uses: actions/checkout@v4
16+
17+
- uses: oven-sh/setup-bun@v1
18+
19+
- name: Build
20+
run: |
21+
bun install
22+
bun run scripts/jsonToDb.js
23+
env:
24+
POSTGRES_URL: ${{ secrets.POSTGRES_URL }}

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
## Problems
2020

21+
### jsonToDb 数据太多上传超时
22+
2123
### Swagger UI cannot display endpoints(SOLVED)
2224

2325
> The bug likely occurs due to the asynchronous nature of the `import()` function used in the `app.register()` calls. When you use `import()` inside `app.register()`, it returns a promise that resolves to the module, and Fastify's `register` method might not be set up to handle promises directly in this manner. This can lead to a race condition where Fastify starts setting up routes before the Swagger plugins are fully registered and configured, resulting in the Swagger UI not being aware of any routes.

bun.lockb

5.07 KB
Binary file not shown.

package.json

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,25 @@
44
"type": "module",
55
"devDependencies": {
66
"@biomejs/biome": "^1.8.2",
7+
"cheerio": "^1.0.0-rc.12",
8+
"dotenv": "^16.4.5",
79
"nodemon": "^3.1.4",
10+
"pino": "^9.2.0",
811
"pino-pretty": "^11.2.1",
9-
"tap": "^19.2.5",
10-
"cheerio": "^1.0.0-rc.12",
11-
"pino": "^9.2.0"
12+
"tap": "^19.2.5"
1213
},
1314
"dependencies": {
1415
"@fastify/autoload": "^5.10.0",
1516
"@fastify/compress": "^7.0.3",
1617
"@fastify/cors": "^9.0.1",
1718
"@fastify/helmet": "^11.1.1",
19+
"@fastify/postgres": "^5.2.2",
1820
"@fastify/rate-limit": "^9.1.0",
1921
"@fastify/swagger": "^8.14.0",
2022
"@fastify/swagger-ui": "^3.1.0",
2123
"@fastify/under-pressure": "^8.5.0",
22-
"fastify": "^4.28.0"
24+
"fastify": "^4.28.0",
25+
"pg": "^8.12.0"
2326
},
2427
"scripts": {
2528
"dev": "export NODE_ENV=development && nodemon .",

routes.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,19 @@ export default async function registerRoutes(app) {
3131
});
3232
});
3333

34+
app.get("/calc", (request, reply) => {
35+
const client = app.pg.connect();
36+
37+
console.log(client);
38+
// const sumResult = client.query < { sum } > "SELECT 2 + 2 as sum";
39+
40+
// client.release();
41+
42+
// return {
43+
// sum: sumResult.rows,
44+
// };
45+
});
46+
3447
createRoute(app, "/books", booksData, { schema: paginationSchema });
3548
createRoute(app, "/feeds", feedsData, { schema: paginationSchema });
3649
createRoute(app, "/movies", moviesData, { schema: paginationSchema });

scripts/jsonToDb.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import * as dotenv from "dotenv";
2+
dotenv.config();
3+
4+
import { Client } from "pg";
5+
6+
// Set up the PostgreSQL client with your configuration
7+
const client = new Client({
8+
connectionString: process.env.POSTGRES_URL,
9+
});
10+
11+
async function createTableIfNotExist(client, tableName) {
12+
const createTableQuery = `
13+
CREATE TABLE IF NOT EXISTS ${tableName} (
14+
id SERIAL PRIMARY KEY,
15+
json_data JSONB NOT NULL
16+
);
17+
`;
18+
await client.query(createTableQuery);
19+
console.log(`Table ${tableName} is ready, or already exists.`);
20+
}
21+
22+
async function truncateTable(client, tableName) {
23+
const truncateQuery = `TRUNCATE TABLE ${tableName};`;
24+
await client.query(truncateQuery);
25+
console.log(`Truncated table ${tableName}`);
26+
}
27+
28+
async function uploadJsonDataFromFile(client, relativePath, tableName) {
29+
try {
30+
const module = await import(`../${relativePath}`);
31+
const jsonDataFromFile = module.default;
32+
33+
await createTableIfNotExist(client, tableName);
34+
await truncateTable(client, tableName);
35+
36+
// Assuming jsonDataFromFile is an array of objects
37+
for (const data of jsonDataFromFile) {
38+
const query = {
39+
text: `INSERT INTO ${tableName}(json_data) VALUES(\$1)`,
40+
values: [JSON.stringify(data)], // Convert data to JSON string
41+
};
42+
await client.query(query);
43+
}
44+
45+
console.log(`Data from ${relativePath} inserted successfully into ${tableName}`);
46+
} catch (err) {
47+
console.error(`Error uploading data from file ${relativePath}:`, err);
48+
}
49+
}
50+
51+
async function uploadAllFiles(client) {
52+
const files = ["books.js", "feeds.js", "movies.js", "music.js", "musicals.js", "prompts.js", "series.js", "words.js"];
53+
54+
for (const file of files) {
55+
const tableName = file.replace('.js', ''); // Remove '.js' to form the table name
56+
await uploadJsonDataFromFile(client, `data/${file}`, tableName);
57+
}
58+
}
59+
60+
async function main() {
61+
try {
62+
await client.connect();
63+
await uploadAllFiles(client);
64+
console.log("Data uploaded successfully");
65+
} catch (err) {
66+
console.error("Error uploading data:", err);
67+
} finally {
68+
await client.end();
69+
console.log("Disconnected from the database.");
70+
}
71+
}
72+
main();

server.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,14 @@ import helmet from "@fastify/helmet";
44
import rateLimit from "@fastify/rate-limit";
55
import swagger from "@fastify/swagger";
66
import swaggerUI from "@fastify/swagger-ui";
7+
import postgres from "@fastify/postgres";
78
import Fastify from "fastify";
89
import pino from "pino";
910
import pretty from "pino-pretty";
1011

12+
import * as dotenv from "dotenv";
13+
dotenv.config();
14+
1115
import registerRoutes from "./routes.js";
1216

1317
// logger
@@ -62,6 +66,11 @@ await app.register(swaggerUI, {
6266
},
6367
});
6468

69+
// database
70+
await app.register(postgres, {
71+
connectionString: process.env.POSTGRES_URL,
72+
});
73+
6574
/// routes
6675
registerRoutes(app);
6776

0 commit comments

Comments
 (0)