create-elysiajs

repository·main·Indexed 41 days ago

https://github.com/kravetsone/create-elysiajs

A scaffolding tool for quickly setting up ElysiaJS projects with pre-configured environments. It supports the bun package manager and provides interactive prompts to configure linters (ESLint, Biome), ORMs (Prisma, Drizzle), Elysia plugins (Swagger, JWT, CORS), and infrastructure tools like Docker and Husky. Version 1.7.0.

Tokens
6K
Snippets
17
Records
23
Agent score
51%

What's inside create-elysiajs

  1. Supported environments and integrations

    main

    The create-elysiajs scaffolding tool supports a wide range of tools that can be configured to work together. When certain tools are selected, they may include automatic cross-tool configurations (e.g., selecting ESLint and Drizzle will include eslint-plugin-drizzle).

    Linters

    • Biome
    • ESLint (using @antfu/eslint-config)

    ORM/Query builders

    • Prisma
    • Drizzle

    Elysia Plugins

    • CORS
    • Swagger
    • JWT
    • Autoload
    • Oauth 2.0
    • HTML/JSX
    • Logger
    • Static
    • Bearer
    • Server Timing

    Testing (bun:test)

    • PGLite (for Postgres mocks)
    • IoRedisMock (for Redis mocks)

    Infrastructure & Utilities

    • Docker (Dockerfile + docker-compose.yml)
    • Jobify (Bullmq wrapper)
    • Posthog
    • Verrou (Locks)
    • Env-var (Environment variables)
    • .vscode (VSCode settings)
    • Husky (Git hooks)
  2. Scaffold an Elysia project with bun create

    main

    Use the bun create elysiajs command to scaffold a new Elysia project. You must provide a directory name as an argument where the project will be generated.

    Note: Currently, support is limited to the bun package manager.

    bun create elysiajs <dir>
  3. Understand Dockerfile generation patterns

    main

    The project generates multi-stage Dockerfiles optimized for Bun or Node.js. The build process follows these stages:

    1. base: Sets the working directory and base image.
    2. install: Creates a temporary directory to install all dependencies (including devDependencies) using a frozen lockfile to ensure cache efficiency.
    3. prerelease: Copies the full project and runs type checking (tsc --noEmit) to ensure code integrity before final packaging.
    4. release: The final production image. It copies only production dependencies (--production) and the necessary source files/configs to minimize image size.

    If an ORM is selected, specific files are copied:

    • Prisma: Copies the ./prisma directory.
    • Drizzle: Copies the ./drizzle directory and drizzle.config.ts.
  4. Configure the test pre-load file for database and Redis mocks

    main

    The scaffolding generates a pre-load file to set up a testing environment using PGlite (an in-memory Postgres) and drizzle-orm. This ensures tests run against a real database instance without needing a separate database server.

    Key features of the pre-load file:

    • Database: Uses @electric-sql/pglite and drizzle-orm/pglite to initialize an in-memory database.
    • Migrations: Automatically runs migrations from the ../drizzle folder using migrate(db, { migrationsFolder: ... }).
    • Redis Mocking: If redis is enabled in your Preferences, it automatically mocks ioredis using ioredis-mock.
    • Driver Mocking: Mocks the database driver and Drizzle instance to point to the pglite instance.
  5. Configure Drizzle ORM database connection

    main

    The project generates a database connection file based on your selected ORM and driver.

    • Prisma: Generates a standard PrismaClient export.
    • Drizzle ORM: Generates a db instance configured with casing: "snake_case". The connection uses the DATABASE_URL from your project's config.ts file.

    Supported driver configurations include:

    • node-postgres (using pg)
    • Postgres.JS (using postgres)
    • Bun.sql (using bun)
    • MySQL 2 (using mysql2)
    • Bun SQLite (using bun:sqlite if using Bun)
    • better-sqlite3 (fallback for SQLite)
    // Example of generated Drizzle + Postgres.JS connection
    import { drizzle } from "drizzle-orm/postgres-js"
    import postgres from "postgres"
    import { config } from "../config.ts"
    
    const client = postgres(config.DATABASE_URL)
    export const db = drizzle({
      client,
      casing: "snake_case",
    })
  6. Configure project features via CLI prompts

    main

    When running the scaffold command, the CLI provides an interactive prompt to customize your project. Key configuration options include:

    Core Configuration

    • Linter/Formatter: Choose between None, ESLint, or Biome.
    • ORM/Query Builder: Choose between None, Prisma, or Drizzle.
      • If Prisma is selected, you can choose from PostgreSQL, MySQL, MongoDB, SQLite, SQLServer, or CockroachDB.
      • If Drizzle is selected, you can choose from PostgreSQL, MySQL, or SQLite.
    • Telegram Support: Option to include Telegram-related validation (e.g., init data).

    Elysia Plugins

    You can select one or more plugins to be pre-configured:

    • CORS, Swagger, JWT, Autoload, Oauth 2.0, HTML/JSX, Static, Bearer, Server Timing.

    Additional Tools & Services

    • Others: S3, Posthog, Jobify, Husky.
    • Database Mocking: If using PostgreSQL with Drizzle, you can enable PGLite (Postgres in WASM) for testing.
    • Infrastructure: Option to generate Dockerfile and docker-compose.yml files.
    • Development: Option to generate .vscode settings and extension recommendations.
  7. Scaffold an ElysiaJS project with bun create

    main

    Use the create-elysiajs CLI to scaffold a new ElysiaJS project. The tool is currently only supported for the bun runtime. You can specify the project directory as a positional argument. During the process, you will be prompted to select various configurations including ORMs, databases, linters, and additional services.

    CLI Arguments

    • dir-name: The name of the folder to create for your project.
    • --pm <package-manager>: Specify the package manager (currently only bun is supported).
    • --monorepo: Flag to indicate the project is part of a monorepo (changes available prompts).
    • --install <boolean>: Whether to run installation commands automatically (defaults to true).
    bun create elysiajs my-new-project
  8. Configure Drizzle Kit for migrations

    main

    The scaffolding tool generates a Drizzle Kit configuration file (typically drizzle.config.ts) to manage schema migrations. It uses env-var to ensure the DATABASE_URL environment variable is present and required.

    import type { Config } from "drizzle-kit"
    import env from "env-var"
    
    const DATABASE_URL = env.get("DATABASE_URL").required().asString()
    
    export default {
      schema: "./src/db/schema.ts",
      out: "./drizzle",
      dialect: "postgres", // or mysql, sqlite, etc.
      casing: "snake_case",
      dbCredentials: {
        url: DATABASE_URL
      }
    } satisfies Config
  9. Configure the Verrou locking service template

    main

    When using the locks.ts service template, the generated verrou instance is configured based on the presence of a redis configuration.

    • Default Behavior: If redis is not provided, the service uses a memory store via memoryStore().
    • Redis Support: If redis is provided in the PreferencesType, the template adds a redis store using redisStore({ connection: redis }) and imports a local ./redis.ts file for the connection.

    The resulting file exports a verrou instance of type Verrou from @verrou/core, which uses a config.LOCK_STORE to determine the default store.

    import { Verrou } from "@verrou/core"
    import { config } from "../config.ts"
    import { memoryStore } from '@verrou/core/drivers/memory'
    
    export const verrou = new Verrou({
        default: config.LOCK_STORE,
        stores: {
            memory: { driver: memoryStore() }
        }
    })
  10. Use the generated API treaty for testing

    main

    When using the create-elysiajs scaffolding, a testing utility file is generated that uses @elysiajs/eden to create a type-safe API client (treaty). This allows you to perform end-to-end testing of your Elysia application by calling your routes as if they were a client-side SDK.

    The generated api.ts file imports your server instance and exports a treaty instance.

    import { treaty } from "@elysiajs/eden";
    import { app } from "../src/server.ts";
    
    export const api = treaty(app);
  11. Use the test shared file for Telegram bot authentication

    main

    The scaffolding includes a getTestSharedFile template which provides utilities for testing features that require Telegram initData. It exports a BOT_TOKEN and a signed INIT_DATA object using @gramio/init-data, allowing you to simulate authenticated Telegram user requests in your tests.

    import { signInitData } from "@gramio/init-data";
    
    export const BOT_TOKEN = "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    export const INIT_DATA = signInitData(
        {
            user: {
                id: 1,
                first_name: "durov",
                username: "durov",
            },
        },
        BOT_TOKEN,
    );
  12. Write API tests using the generated treaty

    main

    The scaffolding provides a template for writing tests using bun:test. You can import the generated api object to test your endpoints. The api object follows the structure of your Elysia routes, allowing for type-safe requests and assertions on status codes and response data.

    Example test structure:

    import { describe, it, expect } from "bun:test";
    import { api } from "../api.ts";
    
    describe("API - /", () => {
        it("/ - should return hello world", async () => {
            const response = await api.index.get();
    
            expect(response.status).toBe(200);
            expect(response.data).toBe("Hello World");
        });
    });