Skip to content

Commit

Permalink
Use mysql2, bump dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
eirslett committed Oct 7, 2024
1 parent 7c8a775 commit 4ce4c75
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 73 deletions.
2 changes: 1 addition & 1 deletion backend/db/setup-local-db.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/bin/sh
echo "Ensuring MySQL database and user exists"
mysql -u root -e "CREATE USER IF NOT EXISTS 'unreed'@'localhost' IDENTIFIED WITH mysql_native_password BY 'unreed'; CREATE DATABASE IF NOT EXISTS unreed; GRANT ALL PRIVILEGES ON unreed.* TO 'unreed'@'localhost'; FLUSH PRIVILEGES;"
mysql -u root -e "CREATE USER IF NOT EXISTS 'unreed'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'unreed'; CREATE DATABASE IF NOT EXISTS unreed; GRANT ALL PRIVILEGES ON unreed.* TO 'unreed'@'localhost'; FLUSH PRIVILEGES;"
echo "Running flyway"
flyway \
-validateMigrationNaming=true \
Expand Down
94 changes: 24 additions & 70 deletions backend/router.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Router } from 'express';
import mysql, { Connection } from 'mysql';
import mysql, { type Connection } from 'mysql2/promise';
import { parseISO } from 'date-fns';

function getConnection() {
async function getConnection() {
if (process.env.NODE_ENV === 'production') {
// Establish a connection to the database
return mysql.createConnection({
Expand All @@ -24,7 +24,7 @@ function getConnection() {
}

async function withConnection<T>(callback: (connection: Connection) => Promise<T>) {
const connection = getConnection();
const connection = await getConnection();
connection.connect();
try {
return await callback(connection);
Expand All @@ -33,18 +33,6 @@ async function withConnection<T>(callback: (connection: Connection) => Promise<T
}
}

async function query(connection: Connection, sql: string, params: any) {
return new Promise((resolve, reject) => {
connection.query(sql, params, function (error, results) {
if (error) {
reject(error);
} else {
resolve(results);
}
});
});
}

export const router = Router();

// This is what we store in the database
Expand All @@ -67,42 +55,6 @@ interface LogEntryBase {
data: Record<string, unknown>;
}

router.get('/api/reed_log.php', (req, res) => {
if (!req.user) {
res.status(401).send({ message: 'Invalid token.' });
return;
}

const connection = getConnection();

connection.connect();
connection.query(
'SELECT entry_id, entry_timestamp, reed_id, entry_type, data, commit_time from reed_log WHERE google_profile_id=? ORDER BY entry_timestamp ASC',
[req.user.email],
function (error, results: ReedLogRow[]) {
if (error) {
console.error(error);
res.status(500).send({ message: 'Something went wrong on the server.' });
connection.end();
} else {
const entries = results.map(
(
// Pick out commit_time from the entry
{ commit_time, ...row },
) => {
return {
...row,
data: JSON.parse(row.data),
};
},
);
res.send(entries);
connection.end();
}
},
);
});

router.post('/api/push', async (req, res) => {
try {
const user = req.user;
Expand All @@ -116,11 +68,12 @@ router.post('/api/push', async (req, res) => {
const conflicts = [];

const ids = changeRows.map((row) => row.newDocumentState.entry_id);
const existingEntries: ReedLogRow[] = (await query(
connection,
'select entry_id, entry_timestamp, reed_id, entry_type, data from reed_log where google_profile_id=? and entry_id in (?)',
[user.email, ids],
)) as ReedLogRow[];
const existingEntries: ReedLogRow[] = (
await connection.query(
'select entry_id, entry_timestamp, reed_id, entry_type, data from reed_log where google_profile_id=? and entry_id in (?)',
[user.email, ids],
)
)[0] as ReedLogRow[];

for (const { entry_id, entry_timestamp, reed_id, entry_type, data } of existingEntries) {
conflicts.push({
Expand All @@ -136,8 +89,7 @@ router.post('/api/push', async (req, res) => {
if (existingEntries.some((row) => row.entry_id === newDocumentState.entry_id)) {
continue;
} else {
const insertResult = (await query(
connection,
await connection.query(
'INSERT INTO reed_log (entry_id, google_profile_id, entry_timestamp, reed_id, entry_type, data) VALUES (?, ?, ?, ?, ?, ?)',
[
newDocumentState.entry_id,
Expand All @@ -147,7 +99,7 @@ router.post('/api/push', async (req, res) => {
newDocumentState.entry_type,
JSON.stringify(newDocumentState.data),
],
)) as { affectedRows: number };
);
}
}

Expand Down Expand Up @@ -193,16 +145,18 @@ router.get('/api/pull', async (req, res) => {
ORDER BY commit_time ASC, entry_timestamp ASC, entry_id ASC
LIMIT ?`;

const results = (await query(connection, queryString, [
user.email,
commitTime,
commitTime,
entryTimestamp,
commitTime,
entryTimestamp,
id,
limit,
])) as ReedLogRow[];
const results = (
await connection.query(queryString, [
user.email,
commitTime,
commitTime,
entryTimestamp,
commitTime,
entryTimestamp,
id,
limit,
])
)[0] as ReedLogRow[];

const entries = results.map(
(
Expand All @@ -212,7 +166,7 @@ router.get('/api/pull', async (req, res) => {
return {
...row,
commit_time,
data: JSON.parse(row.data),
data: row.data,
};
},
);
Expand Down
Binary file modified bun.lockb
Binary file not shown.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"date-fns": "^4.1.0",
"express": "^4.21.0",
"jose": "^5.9.3",
"mysql": "^2.18.1",
"mysql2": "^3.11.3",
"openid-client": "^5.7.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand All @@ -50,7 +50,6 @@
"@storybook/react-vite": "8.3.5",
"@types/bun": "latest",
"@types/cookie-parser": "^1.4.7",
"@types/mysql": "^2.15.26",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.0",
"@types/uuid": "^10.0.0",
Expand Down

0 comments on commit 4ce4c75

Please sign in to comment.