Here's some AI commentary on our database.ts
file to ensure that it's fully typed and follows best practices.
-
Type Annotation for
db
:- We've correctly typed the
db
variable asDatabase<sqlite3.Database, sqlite3.Statement> | null
. This indicates that it can either be aDatabase
object ornull
. However, to improve type safety, we could makedb
non-nullable once it's initialized.
- We've correctly typed the
-
Environment Variables:
- The
dbPath
is currently inferred as astring
, which is fine, but we could explicitly type it to make our code more robust.
- The
-
Function Return Types:
- Our
initDB
function is correctly typed to return aPromise<void>
, and thegetDB
function is also returning the correct type.
- Our
import sqlite3 from 'sqlite3';
import { open, Database } from 'sqlite';
import { config } from 'dotenv';
config(); // Load environment variables
const dbPath: string = process.env.DATABASE_PATH || './dev.db';
let db: Database<sqlite3.Database, sqlite3.Statement> | null = null;
export const initDB = async (): Promise<void> => {
if (!db) {
db = await open({
filename: dbPath,
driver: sqlite3.Database,
});
// Create the `users` table if it doesn't exist
await db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
useremail TEXT UNIQUE NOT NULL,
userid TEXT UNIQUE NOT NULL,
createdAt TEXT DEFAULT CURRENT_TIMESTAMP
)
`);
}
};
export const getDB = (): Database<sqlite3.Database, sqlite3.Statement> => {
if (!db) {
throw new Error('Database not initialized. Call initDB first.');
}
return db;
};
- Type for
dbPath
: We've chosen to explicitly typedbPath
as astring
, which reinforces type safety in our code. - Consistent Typing: The rest of our code is already well-typed, with all functions returning the correct types.
With these adjustments, our database.ts
file is fully typed, ensuring type safety and clarity throughout.