Cosmotype Database Framework
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
-
Error: Driver 'mysql' not found.
cause The required database driver package (e.g., `@cosmotype/driver-mysql`) was not installed or is not resolvable.fixInstall the correct driver package: `npm install @cosmotype/driver-mysql` (replace 'mysql' with your desired driver). -
Error: Connect failed: Access denied for user '...'@'localhost' (using password: YES)
cause Incorrect database connection credentials (username, password) or insufficient user permissions.fixVerify your database host, port, user, password, and database name. Ensure the user has necessary permissions on the database. -
Error: Duplicate entry '1' for key 'user.PRIMARY'
cause Attempting to create a record with a primary key value that already exists in the table without `autoInc` enabled or during an `upsert` operation that isn't configured to update.fixEnsure `autoInc` is set correctly for primary keys if you intend for them to be generated automatically, or handle unique constraint violations explicitly. Use `upsert` if you intend to create or update.
Warnings
- gotcha Cosmotype relies on separate driver packages for database connectivity. Forgetting to install the specific driver (e.g., `@cosmotype/driver-mysql` for MySQL) will result in runtime errors.
- breaking Major version updates of Cosmotype or its drivers may introduce changes to the API, particularly around schema definition syntax or driver options. Always review release notes for breaking changes.
- gotcha While Cosmotype aims to provide a unified API, underlying database-specific behaviors and limitations (e.g., transaction support, advanced indexing, specific data types) may still manifest. Developers should be aware of the chosen driver's capabilities.
Install
-
npm install cosmotype -
yarn add cosmotype -
pnpm add cosmotype
Imports
- Database
import Database from 'cosmotype'
import { Database } from 'cosmotype' - EntitySchemaDefinition
import { EntitySchemaDefinition } from 'cosmotype'import type { EntitySchemaDefinition } from 'cosmotype' - DriverOptions
const DriverOptions = require('cosmotype').DriverOptionsimport type { DriverOptions } from 'cosmotype'
Quickstart
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();