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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x | import { Hono } from "hono";
import { DataDriver, Entity, EntityCollection, FetchCollectionProps } from "@rebasepro/types";
import { QueryOptions, HonoEnv } from "../types";
import { ApiError } from "../errors";
import { parseQueryOptions } from "./query-parser";
import { EntityFetchService } from "../../db/services/EntityFetchService";
import { PostgresDataDriver } from "../../services/postgresDataDriver";
/**
* Lightweight REST API generator that leverages existing Rebase DataDriver.
* Supports `include` query parameter for eager-loading relations via Drizzle.
*/
export class RestApiGenerator {
private collections: EntityCollection[];
private router: Hono<HonoEnv>;
private driver: DataDriver;
constructor(collections: EntityCollection[], driver: DataDriver) {
this.collections = collections;
this.driver = driver;
this.router = new Hono<HonoEnv>();
}
/**
* Generate REST routes using existing DataDriver
*/
generateRoutes(): Hono<HonoEnv> {
this.collections.forEach(collection => {
this.createCollectionRoutes(collection);
});
return this.router;
}
/**
* Get the EntityFetchService from a PostgresDataDriver (for include support)
*/
private getFetchService(driver: DataDriver): EntityFetchService | null {
Iif (driver instanceof PostgresDataDriver) {
return driver.entityService.getFetchService();
}
return null;
}
/**
* Create REST routes for a collection using existing Rebase patterns
*/
private createCollectionRoutes(collection: EntityCollection): void {
const basePath = `/${collection.slug}`;
const resolvedCollection = collection;
// GET /collection - List entities
this.router.get(basePath, async (c) => {
const queryDict = c.req.query();
const queryOptions = parseQueryOptions(queryDict);
const driver = c.get("driver") || this.driver;
const fetchService = this.getFetchService(driver);
// Use include-aware path when available
Iif (fetchService) {
const collectionPath = collection.dbPath || collection.slug;
const entities = await fetchService.fetchCollectionForRest(
collectionPath,
{
filter: queryOptions.where as FetchCollectionProps["filter"],
limit: queryOptions.limit,
orderBy: queryOptions.orderBy?.[0]?.field,
order: queryOptions.orderBy?.[0]?.direction === "desc" ? "desc" : "asc",
searchString: queryDict.searchString as string | undefined,
},
queryOptions.include
);
const total = await this.countRawEntities(driver, resolvedCollection, queryOptions);
return c.json({
data: entities,
meta: {
total,
limit: queryOptions.limit,
offset: queryOptions.offset,
hasMore: (queryOptions.offset || 0) + entities.length < total
}
});
}
// Fallback for non-Postgres drivers
const entities = await this.fetchRawCollection(driver, resolvedCollection, queryOptions);
const total = await this.countRawEntities(driver, resolvedCollection, queryOptions);
return c.json({
data: entities,
meta: {
total,
limit: queryOptions.limit,
offset: queryOptions.offset,
hasMore: (queryOptions.offset || 0) + entities.length < total
}
});
});
// GET /collection/:id - Get single entity
this.router.get(`${basePath}/:id`, async (c) => {
const id = c.req.param("id");
const queryDict = c.req.query();
const queryOptions = parseQueryOptions(queryDict);
const driver = c.get("driver") || this.driver;
const fetchService = this.getFetchService(driver);
// Use include-aware path when available
Iif (fetchService) {
const collectionPath = collection.dbPath || collection.slug;
const entity = await fetchService.fetchEntityForRest(
collectionPath,
String(id),
queryOptions.include
);
Iif (!entity) {
throw ApiError.notFound("Entity not found");
}
return c.json(entity);
}
// Fallback
const entity = await this.fetchRawEntity(driver, resolvedCollection, String(id));
Iif (!entity) {
throw ApiError.notFound("Entity not found");
}
return c.json(entity);
});
// POST /collection - Create entity
this.router.post(basePath, async (c) => {
try {
const driver = c.get("driver") || this.driver;
const path = collection.dbPath || collection.slug;
const body = await c.req.json().catch(() => ({}));
const entity = await driver.saveEntity({
path,
values: body,
collection: resolvedCollection,
status: "new"
});
return c.json(this.formatResponse(entity), 201);
} catch (error) {
const err = error as Error & { code?: string };
err.code = err.code || "BAD_REQUEST";
throw err;
}
});
// PUT /collection/:id - Update entity
this.router.put(`${basePath}/:id`, async (c) => {
try {
const id = c.req.param("id");
const driver = c.get("driver") || this.driver;
const existingEntity = await driver.fetchEntity({
path: collection.dbPath || collection.slug,
entityId: String(id),
collection: resolvedCollection
});
Iif (!existingEntity) {
throw ApiError.notFound("Entity not found");
}
const body = await c.req.json().catch(() => ({}));
const entity = await driver.saveEntity({
path: collection.dbPath || collection.slug,
entityId: String(id),
values: body,
collection: resolvedCollection,
status: "existing"
});
return c.json(this.formatResponse(entity));
} catch (error) {
const err = error as Error & { code?: string };
err.code = err.code || "BAD_REQUEST";
throw err;
}
});
// DELETE /collection/:id - Delete entity
this.router.delete(`${basePath}/:id`, async (c) => {
const id = c.req.param("id");
const driver = c.get("driver") || this.driver;
const existingEntity = await driver.fetchEntity({
path: collection.dbPath || collection.slug,
entityId: String(id),
collection: resolvedCollection
});
Iif (!existingEntity) {
throw ApiError.notFound("Entity not found");
}
await driver.deleteEntity({
entity: existingEntity,
collection: resolvedCollection
});
return new Response(null, { status: 204 });
});
}
/**
* Format successful API response - flattened for traditional REST API
*/
private formatResponse<T>(data: T, meta?: Record<string, unknown>): unknown {
Iif (Array.isArray(data)) {
const flattenedData = data.map(entity => this.flattenEntity(entity));
Iif (meta) {
return {
data: flattenedData,
meta
};
}
return flattenedData;
}
Iif (data && typeof data === "object" && "values" in data) {
return this.flattenEntity(data as unknown as Entity<Record<string, unknown>>);
}
Iif (meta) {
return {
data,
meta
};
}
return data;
}
/**
* Flatten Rebase entity structure to traditional REST format
*/
private flattenEntity(entity: Entity<Record<string, unknown>>): Record<string, unknown> {
Iif (!entity || typeof entity !== "object") {
return entity;
}
Iif ("values" in entity && typeof entity.values === "object") {
return {
id: entity.id,
...entity.values
};
}
return entity as unknown as Record<string, unknown>;
}
/**
* Fetch raw collection data without Entity wrapper (fallback for non-Postgres)
*/
private async fetchRawCollection(driver: DataDriver, collection: EntityCollection, queryOptions: QueryOptions) {
const entities = await driver.fetchCollection({
path: collection.dbPath || collection.slug,
collection,
filter: queryOptions.where as FetchCollectionProps["filter"],
limit: queryOptions.limit,
orderBy: queryOptions.orderBy?.[0]?.field,
order: queryOptions.orderBy?.[0]?.direction === "desc" ? "desc" : "asc",
startAfter: queryOptions.offset ? String(queryOptions.offset) : undefined
});
return entities.map(entity => this.flattenEntity(entity));
}
/**
* Count raw entities for a collection
*/
private async countRawEntities(driver: DataDriver, collection: EntityCollection, queryOptions: QueryOptions): Promise<number> {
return driver.countEntities ? await driver.countEntities({
path: collection.dbPath || collection.slug,
collection,
filter: queryOptions.where as FetchCollectionProps["filter"]
}) : 0;
}
/**
* Fetch single entity raw data without Entity wrapper (fallback)
*/
private async fetchRawEntity(driver: DataDriver, collection: EntityCollection, entityId: string) {
const entity = await driver.fetchEntity({
path: collection.dbPath || collection.slug,
entityId,
collection
});
return entity ? this.flattenEntity(entity) : null;
}
}
|