{"id":24743450,"url":"https://github.com/layerdynamics/rex-orm","last_synced_at":"2025-10-08T19:07:37.068Z","repository":{"id":270425493,"uuid":"910345785","full_name":"LayerDynamics/rex-orm","owner":"LayerDynamics","description":"A modern TypeScript ORM for Deno with PostgreSQL/SQLite support(more coming), real-time sync, GraphQL generation, and seamless serverless deployment. Built for type-safety and developer productivity.","archived":false,"fork":false,"pushed_at":"2025-08-15T22:33:46.000Z","size":1261,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-16T00:32:28.996Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LayerDynamics.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-12-31T03:22:49.000Z","updated_at":"2025-08-15T22:33:50.000Z","dependencies_parsed_at":"2024-12-31T04:26:34.420Z","dependency_job_id":"c11ccb78-3045-41a4-b3e2-0097646626c5","html_url":"https://github.com/LayerDynamics/rex-orm","commit_stats":null,"previous_names":["layerdynamics/rex-orm"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/LayerDynamics/rex-orm","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LayerDynamics%2Frex-orm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LayerDynamics%2Frex-orm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LayerDynamics%2Frex-orm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LayerDynamics%2Frex-orm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LayerDynamics","download_url":"https://codeload.github.com/LayerDynamics/rex-orm/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LayerDynamics%2Frex-orm/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279000701,"owners_count":26082805,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-08T02:00:06.501Z","response_time":56,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-01-28T01:36:10.470Z","updated_at":"2025-10-08T19:07:37.063Z","avatar_url":"https://github.com/LayerDynamics.png","language":"TypeScript","readme":"# Rex-ORM\n\nA robust, type-safe Object-Relational Mapping (ORM) library designed\nspecifically for the Deno runtime environment. Rex-ORM bridges your TypeScript\ncode and relational databases with an elegant, developer-friendly API that\nprioritizes type safety, performance, and real-time capabilities.\n\n## Why Rex-ORM?\n\nRex-ORM goes beyond traditional ORMs by offering:\n\n- **Built for Deno**: Fully leverages Deno's security model and modern\n  JavaScript features\n- **Enterprise-Ready**: Designed for both small projects and large-scale\n  applications\n- **Real-Time First**: Native support for WebSocket-based data synchronization\n- **GraphQL Integration**: Seamlessly expose your data models through GraphQL\n- **Serverless Optimized**: Engineered for cloud-native and serverless\n  deployments\n- **Developer Experience**: Intuitive TypeScript-first API with comprehensive\n  validation\n\nWhether you're building a small API, a complex enterprise application, or a\nreal-time collaborative tool, Rex-ORM provides the database foundation you need\nwithout compromising on performance or type safety.\n\n## Table of Contents\n\n- [Rex-ORM](#rex-orm)\n  - [Table of Contents](#table-of-contents)\n  - [Features](#features)\n  - [Installation](#installation)\n  - [Quick Start](#quick-start)\n  - [Database Configuration](#database-configuration)\n    - [PostgreSQL Configuration](#postgresql-configuration)\n    - [SQLite Configuration](#sqlite-configuration)\n  - [Models](#models)\n    - [Defining Models](#defining-models)\n    - [Relationships](#relationships)\n    - [Validation](#validation)\n  - [Querying](#querying)\n    - [CRUD Operations](#crud-operations)\n    - [Advanced Queries](#advanced-queries)\n    - [Querying Relationships](#querying-relationships)\n  - [Migrations](#migrations)\n    - [Creating Migrations](#creating-migrations)\n    - [Running Migrations](#running-migrations)\n  - [Real-Time Synchronization](#real-time-synchronization)\n    - [Real-Time Setup](#real-time-setup)\n    - [Event Handling](#event-handling)\n  - [GraphQL Integration](#graphql-integration)\n    - [Schema Generation](#schema-generation)\n    - [Custom Resolvers](#custom-resolvers)\n  - [Serverless Deployment](#serverless-deployment)\n    - [Configuration](#configuration)\n    - [Connection Management](#connection-management)\n  - [Plugin System](#plugin-system)\n    - [Creating Plugins](#creating-plugins)\n    - [Using Plugins](#using-plugins)\n  - [Best Practices](#best-practices)\n  - [Contributing](#contributing)\n  - [License](#license)\n  - [Acknowledgments](#acknowledgments)\n  - [Support](#support)\n\n## Features\n\n- **Type-Safe Database Operations**: Leverages TypeScript's type system to catch\n  errors at compile time instead of runtime\n- **Multiple Database Support**: Native adapters for PostgreSQL and SQLite with\n  a plugin system for extending to other databases\n- **Real-Time Synchronization**: Built-in WebSocket server and event system for\n  pushing data changes to connected clients in real-time\n- **GraphQL Integration**: Automatic schema generation from model definitions\n  with customizable resolvers for seamless API creation\n- **Serverless Optimized**: Specialized connection pooling strategies and cold\n  start optimizations for serverless environments\n- **Comprehensive Migration System**: Version-controlled schema changes with\n  robust up/down migrations and tracking\n- **Plugin Architecture**: Extensible plugin system for adding new databases,\n  functionalities, or third-party integrations\n- **Validation System**: Rich decorator-based validation rules with custom\n  validator support and error messaging\n- **Relationship Management**: First-class support for One-to-One, One-to-Many,\n  Many-to-One, and Many-to-Many relationships\n- **Query Builder**: Intuitive fluent API for building complex SQL queries with\n  protection against SQL injection\n- **Connection Pooling**: Smart connection management for optimal database\n  performance under varying loads\n- **Transaction Support**: First-class ACID-compliant transaction handling with\n  automatic rollback on errors\n\n## Installation\n\nRex-ORM is designed specifically for Deno, making it easy to integrate into your\nprojects.\n\n### Prerequisites\n\n- Deno 1.34.0 or newer\n- Database server (PostgreSQL 12+ or SQLite 3.38+)\n\n### Local Installation\n\nSince Rex-ORM is not currently on deno.land but will be available on JSR in the\nfuture, you can use it by cloning the repository:\n\n```bash\n# Clone the repository\ngit clone https://github.com/username/rex-orm.git\n```\n\nImport it in your project:\n\n```typescript\n// deps.ts\nexport {\n  BaseModel,\n  Column,\n  Entity,\n  ManyToMany,\n  ManyToOne,\n  Model,\n  OneToMany,\n  // Relationships\n  OneToOne,\n  PrimaryKey,\n  QueryBuilder,\n  // Validation\n  Validate,\n  ValidateMultiple,\n} from \"./path/to/rex-orm/mod.ts\";\n```\n\n### Future JSR Installation\n\nWhen Rex-ORM becomes available on JSR, you'll be able to import it directly:\n\n```typescript\n// deps.ts\nexport {\n  BaseModel,\n  Column,\n  Entity,\n  ManyToMany,\n  ManyToOne,\n  Model,\n  OneToMany,\n  // Relationships\n  OneToOne,\n  PrimaryKey,\n  QueryBuilder,\n  // Validation\n  Validate,\n  ValidateMultiple,\n} from \"@jsr/rex-orm/mod.ts\";\n```\n\n### Editor Integration\n\nFor the best development experience, set up your editor with proper Deno\nconfiguration:\n\n```json\n// .vscode/settings.json\n{\n  \"deno.enable\": true,\n  \"deno.lint\": true,\n  \"editor.formatOnSave\": true,\n  \"[typescript]\": {\n    \"editor.defaultFormatter\": \"denoland.vscode-deno\"\n  }\n}\n```\n\n### Project Setup\n\nIf you're starting a new project, our CLI can help you set up the basic\nstructure:\n\n```bash\ndeno run --allow-read --allow-write https://deno.land/x/rex_orm@v1.0.0/cli.ts init\n```\n\nThis will create the following structure:\n\n```\nmy-project/\n├── config/\n│   └── default.json      # Database configuration\n├── migrations/           # Database migrations\n├── models/               # Your data models\n├── deps.ts               # Dependencies\n├── main.ts               # Application entry point\n└── deno.json             # Deno configuration\n```\n\n## Quick Start\n\nRex-ORM is designed to get you productive quickly while providing a path to\nadvanced usage as your application grows.\n\n### Basic Setup\n\n1. **Define your models** - Create TypeScript classes that map to your database\n   tables:\n\n```typescript\nimport {\n  BaseModel,\n  Column,\n  Model,\n  PrimaryKey,\n} from \"https://deno.land/x/rex_orm@v1.0.0/mod.ts\";\n\n@Model({ tableName: \"users\" })\nexport class User extends BaseModel {\n  @PrimaryKey()\n  id!: number;\n\n  @Column({ type: \"varchar\", length: 255 })\n  name!: string;\n\n  @Column({ type: \"varchar\", length: 255, unique: true })\n  email!: string;\n\n  @Column({ type: \"timestamp\", defaultValue: \"CURRENT_TIMESTAMP\" })\n  createdAt!: Date;\n}\n```\n\n2. **Configure database connection** - Connect to your database with type-safe\n   configuration:\n\n```typescript\nimport { DatabaseFactory } from \"https://deno.land/x/rex_orm@v1.0.0/mod.ts\";\n\n// Load configuration from environment or config file\nconst config = {\n  database: \"postgres\",\n  host: Deno.env.get(\"DB_HOST\") || \"localhost\",\n  port: Number(Deno.env.get(\"DB_PORT\")) || 5432,\n  username: Deno.env.get(\"DB_USER\") || \"postgres\",\n  password: Deno.env.get(\"DB_PASSWORD\") || \"postgres\",\n  databaseName: Deno.env.get(\"DB_NAME\") || \"my_app\",\n  // Connection pooling options\n  poolSize: 10,\n  idleTimeout: 30000,\n};\n\n// Create and initialize database adapter\nconst adapter = DatabaseFactory.createAdapter(config);\nawait adapter.connect();\n```\n\n3. **Perform CRUD operations** - Interact with your database using models and\n   the query builder:\n\n```typescript\n// CREATE: Insert a new user\nconst user = new User();\nuser.name = \"Jane Doe\";\nuser.email = \"jane@example.com\";\nawait user.save(adapter);\nconsole.log(`Created user with ID: ${user.id}`);\n\n// READ: Query users with the fluent query builder\nimport { QueryBuilder } from \"https://deno.land/x/rex_orm@v1.0.0/mod.ts\";\n\nconst qb = new QueryBuilder();\nconst recentUsers = await qb\n  .select([\"id\", \"name\", \"email\", \"createdAt\"])\n  .from(\"users\")\n  .where(\"createdAt\", \"\u003e\", new Date(Date.now() - 24 * 60 * 60 * 1000)) // Last 24 hours\n  .orderBy(\"createdAt\", \"DESC\")\n  .limit(10)\n  .execute(adapter);\n\nconsole.log(`Found ${recentUsers.rows.length} recent users`);\n\n// UPDATE: Modify an existing user\nconst userToUpdate = await User.findById(1, adapter);\nif (userToUpdate) {\n  userToUpdate.name = \"Jane Smith\";\n  await userToUpdate.save(adapter);\n  console.log(\"User updated successfully\");\n}\n\n// DELETE: Remove a user from the database\nconst userToDelete = await User.findById(2, adapter);\nif (userToDelete) {\n  await userToDelete.delete(adapter);\n  console.log(\"User deleted successfully\");\n}\n```\n\n### Complete Application Example\n\nHere's a complete example of a basic RESTful API using Rex-ORM with Deno's HTTP\nserver:\n\n```typescript\n// app.ts\nimport { serve } from \"https://deno.land/std@0.200.0/http/server.ts\";\nimport {\n  BaseModel,\n  Column,\n  DatabaseFactory,\n  Model,\n  PrimaryKey,\n  QueryBuilder,\n} from \"https://deno.land/x/rex_orm@v1.0.0/mod.ts\";\n\n// 1. Define model\n@Model({ tableName: \"tasks\" })\nclass Task extends BaseModel {\n  @PrimaryKey()\n  id!: number;\n\n  @Column({ type: \"varchar\", length: 255 })\n  title!: string;\n\n  @Column({ type: \"text\", nullable: true })\n  description?: string;\n\n  @Column({ type: \"boolean\", defaultValue: \"false\" })\n  completed!: boolean;\n\n  @Column({ type: \"timestamp\", defaultValue: \"CURRENT_TIMESTAMP\" })\n  createdAt!: Date;\n}\n\n// 2. Database setup\nconst adapter = DatabaseFactory.createAdapter({\n  database: \"sqlite\",\n  databasePath: \"./tasks.sqlite\",\n});\n\n// 3. Create initial schema\nawait adapter.connect();\nawait adapter.execute(`\n  CREATE TABLE IF NOT EXISTS tasks (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    title TEXT NOT NULL,\n    description TEXT,\n    completed BOOLEAN NOT NULL DEFAULT 0,\n    createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n  )\n`);\n\n// 4. HTTP server with REST endpoints\nconst handler = async (req: Request): Promise\u003cResponse\u003e =\u003e {\n  const url = new URL(req.url);\n  const path = url.pathname;\n\n  // GET /tasks - List all tasks\n  if (path === \"/tasks\" \u0026\u0026 req.method === \"GET\") {\n    const qb = new QueryBuilder();\n    const result = await qb.select(\"*\").from(\"tasks\").execute(adapter);\n    return new Response(JSON.stringify(result.rows), {\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  }\n\n  // POST /tasks - Create a new task\n  if (path === \"/tasks\" \u0026\u0026 req.method === \"POST\") {\n    try {\n      const body = await req.json();\n      const task = new Task();\n      task.title = body.title;\n      task.description = body.description;\n      await task.save(adapter);\n\n      return new Response(JSON.stringify(task), {\n        status: 201,\n        headers: { \"Content-Type\": \"application/json\" },\n      });\n    } catch (error) {\n      return new Response(JSON.stringify({ error: error.message }), {\n        status: 400,\n        headers: { \"Content-Type\": \"application/json\" },\n      });\n    }\n  }\n\n  // GET /tasks/:id - Get a specific task\n  if (path.match(/^\\/tasks\\/\\d+$/) \u0026\u0026 req.method === \"GET\") {\n    const id = parseInt(path.split(\"/\")[2]);\n    const task = await Task.findById(id, adapter);\n\n    if (!task) {\n      return new Response(JSON.stringify({ error: \"Task not found\" }), {\n        status: 404,\n        headers: { \"Content-Type\": \"application/json\" },\n      });\n    }\n\n    return new Response(JSON.stringify(task), {\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  }\n\n  // Default: Not found\n  return new Response(JSON.stringify({ error: \"Not found\" }), {\n    status: 404,\n    headers: { \"Content-Type\": \"application/json\" },\n  });\n};\n\n// 5. Start the server\nconsole.log(\"Server running on http://localhost:8000\");\nawait serve(handler, { port: 8000 });\n```\n\nRun the example with:\n\n```bash\ndeno run --allow-net --allow-read --allow-write app.ts\n```\n\n## Database Configuration\n\nRex-ORM supports both PostgreSQL and SQLite. Configure your database connection\nbased on your needs:\n\n### PostgreSQL Configuration\n\n```typescript\nconst config = {\n  database: \"postgres\",\n  host: \"localhost\",\n  port: 5432,\n  username: \"user\",\n  password: \"password\",\n  databaseName: \"my_app\",\n  poolSize: 10, // Optional: Connection pool size\n  idleTimeout: 30000, // Optional: Idle timeout in milliseconds\n};\n```\n\n### SQLite Configuration\n\n```typescript\nconst config = {\n  database: \"sqlite\",\n  databasePath: \"./data/database.sqlite\",\n};\n```\n\n## Models\n\n### Defining Models\n\nModels represent your database tables and are defined using decorators:\n\n```typescript\n@Model({ tableName: \"posts\" })\nexport class Post extends BaseModel {\n  @PrimaryKey()\n  id!: number;\n\n  @Column({ type: \"varchar\", length: 255 })\n  title!: string;\n\n  @Column({ type: \"text\" })\n  content!: string;\n\n  @Column({ type: \"timestamp\", nullable: true })\n  publishedAt?: Date;\n\n  @ManyToOne(() =\u003e User, (user) =\u003e user.posts)\n  author!: User;\n}\n```\n\n### Relationships\n\nRex-ORM supports all standard relationship types:\n\n```typescript\n// One-to-Many\n@OneToMany(() =\u003e Post, (post) =\u003e post.author)\nposts!: Post[];\n\n// Many-to-One\n@ManyToOne(() =\u003e User, (user) =\u003e user.posts)\nauthor!: User;\n\n// One-to-One\n@OneToOne(() =\u003e Profile, (profile) =\u003e profile.user)\nprofile!: Profile;\n\n// Many-to-Many\n@ManyToMany(() =\u003e Tag, (tag) =\u003e tag.posts)\ntags!: Tag[];\n```\n\n### Validation\n\nAdd validation rules using decorators:\n\n```typescript\n@Model({ tableName: \"users\" })\nexport class User extends BaseModel {\n  @Column({ type: \"varchar\", length: 255 })\n  @Validate({\n    validator: (value: string) =\u003e value.length \u003e= 3,\n    message: \"Name must be at least 3 characters long\",\n  })\n  name!: string;\n\n  @Column({ type: \"varchar\", length: 255 })\n  @ValidateMultiple([\n    {\n      validator: (value: string) =\u003e /^[^@]+@[^@]+\\.[^@]+$/.test(value),\n      message: \"Invalid email format\",\n    },\n    {\n      validator: (value: string) =\u003e value.length \u003c= 255,\n      message: \"Email cannot exceed 255 characters\",\n    },\n  ])\n  email!: string;\n}\n```\n\n## Querying\n\n### CRUD Operations\n\n```typescript\n// Create\nconst post = new Post();\npost.title = \"Hello World\";\npost.content = \"First post content\";\nawait post.save(adapter);\n\n// Read\nconst qb = new QueryBuilder();\nconst posts = await qb\n  .select([\"id\", \"title\", \"content\"])\n  .from(\"posts\")\n  .where(\"title\", \"LIKE\", \"%Hello%\")\n  .orderBy(\"createdAt\", \"DESC\")\n  .limit(10)\n  .execute(adapter);\n\n// Update\nconst post = await Post.findById(1);\npost.title = \"Updated Title\";\nawait post.save(adapter);\n\n// Delete\nawait post.delete(adapter);\n```\n\n### Advanced Queries\n\n```typescript\nconst qb = new QueryBuilder();\n\n// Complex conditions\nconst results = await qb\n  .select([\"posts.*\", \"users.name AS author_name\"])\n  .from(\"posts\")\n  .join(\"users\", \"users.id = posts.author_id\")\n  .where(\"posts.published\", \"=\", true)\n  .andWhere(\"posts.created_at\", \"\u003e\", new Date(\"2023-01-01\"))\n  .orderBy(\"posts.created_at\", \"DESC\")\n  .limit(20)\n  .offset(40)\n  .execute(adapter);\n\n// Aggregations\nconst stats = await qb\n  .select([\n    \"COUNT(*) as total_posts\",\n    \"AVG(view_count) as avg_views\",\n  ])\n  .from(\"posts\")\n  .groupBy(\"author_id\")\n  .having(\"COUNT(*)\", \"\u003e\", 5)\n  .execute(adapter);\n```\n\n### Querying Relationships\n\n```typescript\n// Eager loading\nconst postsWithAuthor = await qb\n  .select([\"posts.*\", \"users.*\"])\n  .from(\"posts\")\n  .join(\"users\", \"users.id = posts.author_id\")\n  .where(\"posts.published\", \"=\", true)\n  .execute(adapter);\n\n// Lazy loading\nconst post = await Post.findById(1);\nconst author = await post.author; // Loads author when accessed\n```\n\n## Migrations\n\n### Creating Migrations\n\nCreate a new migration:\n\n```bash\ndeno run --allow-read --allow-write cli.ts migration:create add_published_flag_to_posts\n```\n\nThis creates a migration file:\n\n```typescript\n// migrations/20240101000000_add_published_flag_to_posts.ts\nimport { Migration } from \"../types.ts\";\n\nconst migration: Migration = {\n  id: \"20240101000000_add_published_flag_to_posts\",\n  up: async (adapter) =\u003e {\n    await adapter.execute(`\n      ALTER TABLE posts\n      ADD COLUMN published BOOLEAN NOT NULL DEFAULT FALSE\n    `);\n  },\n  down: async (adapter) =\u003e {\n    await adapter.execute(`\n      ALTER TABLE posts\n      DROP COLUMN published\n    `);\n  },\n};\n\nexport default migration;\n```\n\n### Running Migrations\n\n```bash\n# Apply pending migrations\ndeno run --allow-read --allow-write cli.ts migrate:up\n\n# Rollback last migration\ndeno run --allow-read --allow-write cli.ts migrate:down\n\n# Reset database\ndeno run --allow-read --allow-write cli.ts migrate:reset\n```\n\n## Real-Time Synchronization\n\n### Real-Time Setup\n\n```typescript\nimport { RealTimeSync } from \"./deps.ts\";\n\nconst realTimeSync = new RealTimeSync({\n  port: 8080,\n});\n\nawait realTimeSync.start();\n\n// Enable real-time updates for models\nBaseModel.initializeRealTimeSync(realTimeSync);\n```\n\n### Event Handling\n\n```typescript\n// Server-side event emission\n@Model({ tableName: \"posts\" })\nexport class Post extends BaseModel {\n  async save(adapter: DatabaseAdapter) {\n    await super.save(adapter);\n    realTimeSync.getEventEmitter().emit({\n      type: \"POST_UPDATED\",\n      payload: this.toJSON(),\n    });\n  }\n}\n\n// Client-side event handling\nconst ws = new WebSocket(\"ws://localhost:8080\");\n\nws.onmessage = (event) =\u003e {\n  const { type, payload } = JSON.parse(event.data);\n  switch (type) {\n    case \"POST_UPDATED\":\n      updateUI(payload);\n      break;\n  }\n};\n```\n\n## GraphQL Integration\n\n### Schema Generation\n\n```typescript\nimport { GraphQLSchemaGenerator } from \"./deps.ts\";\n\n// Generate schema from models\nconst schemaConfig = GraphQLSchemaGenerator.generateSchemaConfig();\n\n// Create GraphQL server\nconst server = new GraphQLServerWrapper(schemaConfig, {\n  adapter,\n}, {\n  port: 4000,\n});\n\nawait server.start();\n```\n\n### Custom Resolvers\n\n```typescript\nconst resolvers = {\n  Query: {\n    async getPost(_: any, { id }: { id: string }, context: any) {\n      const post = await Post.findById(id);\n      return post;\n    },\n  },\n  Mutation: {\n    async createPost(_: any, { input }: { input: any }, context: any) {\n      const post = new Post();\n      Object.assign(post, input);\n      await post.save(context.adapter);\n      return post;\n    },\n  },\n};\n```\n\n## Serverless Deployment\n\n### Configuration\n\n```typescript\n// serverless.yml\nservice: rex-orm-api\n\nprovider:\n  name: aws\n  runtime: provided.al2\n  memorySize: 1024\n  timeout: 30\n\nfunctions:\n  graphql:\n    handler: handler.graphqlHandler\n    events:\n      - http:\n          path: graphql\n          method: post\n          cors: true\n\n  realtime:\n    handler: handler.realtimeHandler\n    events:\n      - websocket:\n          route: $connect\n      - websocket:\n          route: $disconnect\n      - websocket:\n          route: $default\n```\n\n### Connection Management\n\n```typescript\nimport { StatelessPoolManager } from \"./deps.ts\";\n\n// Initialize connection pool\nStatelessPoolManager.initialize({\n  database: \"postgres\",\n  maxConnections: 10,\n  idleTimeout: 30000,\n});\n\n// Get connection\nconst connection = await StatelessPoolManager.getConnection();\ntry {\n  // Use connection\n} finally {\n  await StatelessPoolManager.releaseConnection(connection);\n}\n```\n\n- This project supports AWS Lambda deployment via the Serverless Framework.\n- We provide a deploy.sh script under src/serverless for easy setup:\n  - Installs Serverless if missing.\n  - Installs required plugins.\n  - Runs \"serverless deploy\".\n- Configure AWS credentials before deploying (aws configure).\n- Adjust memory, timeout, and region in serverless.yml as needed.\n\n## Plugin System\n\n### Creating Plugins\n\n```typescript\nimport { Plugin } from \"./deps.ts\";\n\nexport class MySQLPlugin implements Plugin {\n  name = \"mysql\";\n\n  initialize() {\n    // Register MySQL adapter\n    DatabaseFactory.registerAdapter(\"mysql\", MySQLAdapter);\n  }\n}\n```\n\n### Using Plugins\n\n```typescript\nimport { ORM } from \"./deps.ts\";\nimport { MySQLPlugin } from \"./plugins/mysql.ts\";\n\n// Initialize ORM with plugins\nORM.initialize([\n  new MySQLPlugin(),\n]);\n```\n\n## Best Practices\n\n1. **Model Organization**\n   - Keep models in separate files\n   - Use clear, descriptive names\n   - Document complex relationships\n\n2. **Query Optimization**\n   - Use appropriate indexes\n   - Limit result sets\n   - Use eager loading for relationships\n\n3. **Migration Management**\n   - One change per migration\n   - Include both up and down migrations\n   - Test migrations before production\n\n4. **Error Handling**\n   - Implement proper error handling\n   - Use custom error classes\n   - Log errors appropriately\n\n5. **Real-Time Updates**\n   - Implement proper reconnection logic\n   - Handle connection failures\n   - Use appropriate event types\n\n6. **Security**\n   - Validate input data\n   - Use parameterized queries\n   - Implement proper authentication\n\n## Contributing\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/AmazingFeature`)\n3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)\n4. Push to the branch (`git push origin feature/AmazingFeature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file\nfor details.\n\n## Acknowledgments\n\n- Deno community for their excellent standard library\n- GraphQL Deno for GraphQL support\n- Contributors who have helped shape this project\n\n## Support\n\nFor support, please:\n\n- Open an issue on GitHub\n- Join our Discord community\n- Check the documentation\n- Contact the maintainers\n\nFor commercial support options, please contact the maintainers directly.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flayerdynamics%2Frex-orm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flayerdynamics%2Frex-orm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flayerdynamics%2Frex-orm/lists"}