Skip to content

Instantly share code, notes, and snippets.

@exonomyapp
Created August 26, 2024 15:53
Show Gist options
  • Save exonomyapp/fb875a51da269b37e8cbfbe1f1b1c2eb to your computer and use it in GitHub Desktop.
Save exonomyapp/fb875a51da269b37e8cbfbe1f1b1c2eb to your computer and use it in GitHub Desktop.
AI Commentary on How to Fully Type database.ts

Here's some AI commentary on our database.ts file to ensure that it's fully typed and follows best practices.

Analysis and Improvements:

  1. Type Annotation for db:

    • We've correctly typed the db variable as Database<sqlite3.Database, sqlite3.Statement> | null. This indicates that it can either be a Database object or null. However, to improve type safety, we could make db non-nullable once it's initialized.
  2. Environment Variables:

    • The dbPath is currently inferred as a string, which is fine, but we could explicitly type it to make our code more robust.
  3. Function Return Types:

    • Our initDB function is correctly typed to return a Promise<void>, and the getDB function is also returning the correct type.

Suggested Updated Code:

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;
};

Key Points:

  • Type for dbPath: We've chosen to explicitly type dbPath as a string, 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment