All files / src/api server.ts

66.19% Statements 47/71
22.5% Branches 9/40
29.41% Functions 5/17
68.11% Lines 47/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 2472x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x           2x             12x                     12x   12x 12x   12x             12x   12x       12x 12x   12x     12x 12x   12x               12x         12x                     12x                     12x     12x                   12x                                       12x 12x 12x     12x         12x 12x                                                     12x 3x 3x 3x       12x                       12x           12x 12x                                                                     12x                              
import { Hono } from "hono";
import { cors } from "hono/cors";
import { secureHeaders } from "hono/secure-headers";
import { graphqlServer } from "@hono/graphql-server";
import { serve } from "@hono/node-server";
import { GraphQLSchemaGenerator } from "./graphql/graphql-schema-generator";
import { RestApiGenerator } from "./rest/api-generator";
import { DataDriver, EntityCollection, Relation } from "@rebasepro/types";
import { ApiConfig, HonoEnv } from "./types";
import { loadCollectionsFromDirectory } from "../collections/loader";
import { createSchemaEditorRoutes } from "./schema-editor-routes";
import { createAuthMiddleware, requireAuth, requireAdmin } from "../auth/middleware";
import { errorHandler } from "./errors";
import { generateOpenApiSpec } from "./openapi-generator";
 
/**
 * Simplified API server that leverages existing Rebase infrastructure
 * Can be used standalone or mounted on existing Hono app
 */
export class RebaseApiServer {
    private app: Hono<HonoEnv>;
    private router: Hono<HonoEnv>;
    private config: ApiConfig;
    private driver: DataDriver;
 
    private constructor(config: ApiConfig & { driver: DataDriver }) {
        this.config = {
            basePath: "/api",
            enableGraphQL: true,
            enableREST: true,
            pagination: {
                defaultLimit: 20,
                maxLimit: 100
            },
            ...config
        };
 
        this.driver = config.driver;
 
        this.app = new Hono<HonoEnv>();
        this.router = new Hono<HonoEnv>();
        
        this.setupMiddleware();
    }
 
    /**
     * Factory method to create an asynchronously initialized ApiServer instance
     */
    public static async create(config: ApiConfig & { driver: DataDriver }): Promise<RebaseApiServer> {
        Iif (config.collectionsDir && (!config.collections || config.collections.length === 0)) {
            config.collections = await loadCollectionsFromDirectory(config.collectionsDir);
        } else Iif (!config.collections) {
            config.collections = [];
        }
 
        const server = new RebaseApiServer(config);
        server.setupRoutes();
        // Since we mount routes directly to router, we can let consumer attach it
        server.app.route("/", server.router);
        
        // Hono global error handler on the root app
        server.app.onError(errorHandler);
        server.router.onError(errorHandler);
 
        return server;
    }
 
    /**
     * Setup Hono middleware
     */
    private setupMiddleware(): void {
        // Security headers
        this.router.use("/*", secureHeaders());
 
        // CORS — only applied if explicitly configured via `cors` option.
        // If omitted, the user is expected to configure CORS on their own
        // Hono app before mounting the API (recommended approach).
        Iif (this.config.cors) {
            const origin = this.config.cors.origin;
            this.router.use("/*", cors({
                origin: typeof origin === "boolean"
                    ? (origin ? ((o: string) => o) : "")
                    : (origin ?? "*"),
                credentials: this.config.cors.credentials ?? false
            }));
        }
 
        // Auth middleware
        this.router.use("/*", createAuthMiddleware({
            driver: this.driver,
            requireAuth: this.config.requireAuth ?? true,
            validator: this.config.authValidator
        }));
    }
 
    /**
     * Setup API routes using existing services
     */
    private setupRoutes(): void {
        const basePath = this.config.basePath!;
 
        // Health check
        this.router.get(`${basePath}/health`, (c) => {
            return c.json({
                status: "healthy",
                timestamp: new Date().toISOString(),
                collections: this.config.collections?.map((col: EntityCollection) => col.slug) || [],
                driver: this.driver.key
            });
        });
 
        // Collections metadata endpoint
        this.router.get(`${basePath}/collections`, (c) => {
            const collectionsMetadata = (this.config.collections || []).map((col: EntityCollection) => ({
                slug: col.slug,
                name: col.name,
                singularName: col.singularName,
                description: col.description,
                dbPath: col.dbPath,
                properties: Object.keys(col.properties),
                relations: col.relations?.map((r: Relation) => ({
                    relationName: r.relationName,
                    target: typeof r.target === 'function' ? r.target().slug : r.target,
                    cardinality: r.cardinality,
                    direction: r.direction
                })) || []
            }));
 
            return c.json({ data: collectionsMetadata });
        });
 
        // GraphQL endpoint
        if (this.config.enableGraphQL) {
            const schemaGenerator = new GraphQLSchemaGenerator(this.config.collections || [], this.driver);
            const schema = schemaGenerator.generateSchema();
 
            // Context is automatically passed to resolvers via contextValue containing Hono's 'c'
            this.router.use(`${basePath}/graphql`, graphqlServer({
                schema
            }));
 
            // Lightweight GraphiQL IDE
            if (process.env.NODE_ENV !== "production") {
                this.router.get(`${basePath}/graphiql`, (c) => {
                    return c.html(`<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8/>
  <title>Rebase GraphiQL</title>
  <link rel="stylesheet" href="https://unpkg.com/graphiql/graphiql.min.css" />
  <style>body,html,#graphiql{height:100%;margin:0;width:100%;}</style>
</head>
<body>
<div id="graphiql">Loading...</div>
<script crossorigin src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/graphiql/graphiql.min.js"></script>
<script>
  const fetcher = GraphiQL.createFetcher({ url: '${basePath}/graphql' });
  ReactDOM.render(
    React.createElement(GraphiQL, { fetcher }),
    document.getElementById('graphiql'),
  );
</script>
</body>
</html>`);
                });
            }
        }
 
        if (this.config.enableREST) {
            const restGenerator = new RestApiGenerator(this.config.collections || [], this.driver);
            const restRoutes = restGenerator.generateRoutes();
            this.router.route(basePath, restRoutes);
        }
 
        // Schema Editor endpoints
        Iif (this.config.collectionsDir) {
            if (process.env.NODE_ENV === "production") {
                console.warn("[RebaseApiServer] Schema Editor is disabled in production environments for security.");
            } else {
                const schemaEditorRoutes = createSchemaEditorRoutes(this.config.collectionsDir);
                this.router.route(`${basePath}/schema-editor`, schemaEditorRoutes);
                // Auth middlewares applied to schema-editor via the router prefix
                this.router.use(`${basePath}/schema-editor/*`, requireAuth, requireAdmin);
            }
        }
 
        // OpenAPI endpoint
        this.router.get(`${basePath}/docs`, (c) => {
            const openApiSpec = generateOpenApiSpec(this.config.collections || [], this.config.basePath);
            return c.json(openApiSpec);
        });
 
        // Simple Swagger UI
        if (process.env.NODE_ENV !== "production") {
            this.router.get(`${basePath}/swagger`, (c) => {
                return c.html(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>Rebase API Documentation</title>
                        <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@4.15.5/swagger-ui.css" />
                    </head>
                    <body>
                        <div id="swagger-ui"></div>
                        <script src="https://unpkg.com/swagger-ui-dist@4.15.5/swagger-ui-bundle.js"></script>
                        <script>
                            SwaggerUIBundle({
                                url: '${basePath}/docs',
                                dom_id: '#swagger-ui'
                            });
                        </script>
                    </body>
                    </html>
                `);
            });
        }
    }
 
    /**
     * Get the Hono router with all API routes
     */
    getRouter(): Hono<HonoEnv> {
        return this.router;
    }
 
    /**
     * Get the standalone Hono app
     */
    getApp(): Hono<HonoEnv> {
        return this.app;
    }
 
    /**
     * Start the server (standalone mode) via @hono/node-server
     */
    listen(port: number = 3000, callback?: () => void): void {
        serve({
            fetch: this.app.fetch,
            port
        }, () => {
            Iif (callback) callback();
        });
    }
}