Cosmotype Database Framework

1.0.10 · active · verified Wed Apr 22

Cosmotype is a type-driven database framework designed to offer a unified API for interacting with various database systems, abstracting away driver-specific complexities. It is built with TypeScript, providing comprehensive type support for schema definitions and operations, which helps in preventing common data-related errors at compile time. Currently at version 1.0.10, the project appears to be actively maintained, though no explicit release cadence is specified. A key differentiator is its ability to perform advanced database operations, akin to full SQL capabilities, even when interfacing with NoSQL databases like MongoDB or key-value stores like LevelDB, all through a consistent JavaScript/TypeScript API. This makes it highly versatile and extensible, supporting simultaneous access to different databases and even enabling low-code operations in browser environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to a MySQL database, defining a user schema, and performing create and get operations with type safety.

import { Database } from 'cosmotype';
import type { EntitySchemaDefinition } from 'cosmotype';

interface User {
  id: number;
  name: string;
  age: number;
  money: number;
}

async function runCosmotypeExample() {
  const database = new Database();

  // Ensure you have @cosmotype/driver-mysql installed and a MySQL server running
  // For demonstration, we'll use a placeholder for environment variables.
  try {
    await database.connect('mysql', {
      host: process.env.DB_HOST ?? 'localhost',
      port: parseInt(process.env.DB_PORT ?? '3306'),
      user: process.env.DB_USER ?? 'root',
      password: process.env.DB_PASSWORD ?? 'password',
      database: process.env.DB_NAME ?? 'cosmotype_db',
    });
    console.log('Connected to MySQL database.');

    const userSchema: EntitySchemaDefinition = {
      id: 'number',
      name: 'string',
      age: 'number',
      money: { type: 'number', initial: 100 }
    };

    database.extend<User>('user', userSchema, {
      primary: 'id',
      autoInc: true,
    });
    console.log('User schema extended.');

    const newUser = await database.create<User>('user', {
      name: 'Alice',
      age: 30,
    });
    console.log('Created new user:', newUser);

    const retrievedUser = await database.get<User>('user', { id: newUser.id });
    console.log('Retrieved user:', retrievedUser);

  } catch (error) {
    console.error('Cosmotype example failed:', error);
  } finally {
    // In a real application, you'd likely disconnect or keep the connection alive.
    // await database.disconnect();
    console.log('Example finished.');
  }
}

runCosmotypeExample();

view raw JSON →