All files / src/api/graphql graphql-schema-generator.ts

58.71% Statements 64/109
28.33% Branches 17/60
70.83% Functions 17/24
60.95% Lines 64/105

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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 3292x                                   2x     12x 12x     12x 12x               12x 12x 12x     12x 12x   12x                   12x   12x       12x     12x             12x 30x 21x 21x 21x       12x     12x     12x 12x           21x   12x 12x   9x 9x                           21x             12x   12x       12x   12x 30x 30x           12x           12x 12x       30x   21x   9x                               12x   12x 12x 12x   12x     12x                                 12x                                                                   12x                   12x   12x 12x 12x 12x   12x     12x                                     12x                                       12x                                                   12x               60x         12x       12x      
import {
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLString,
    GraphQLInt,
    GraphQLFloat,
    GraphQLBoolean,
    GraphQLList,
    GraphQLNonNull,
    GraphQLFieldConfig,
    GraphQLInputObjectType,
} from "graphql";
import { DataDriver, EntityCollection, FetchCollectionProps, Property } from "@rebasepro/types";
 
/**
 * Lightweight GraphQL schema generator that leverages existing DataDriver
 * No duplication - uses your existing data layer and services
 */
export class GraphQLSchemaGenerator {
    private collections: EntityCollection[];
    private driver: DataDriver;
    private typeRegistry = new Map<string, GraphQLObjectType>();
    private inputTypeRegistry = new Map<string, GraphQLInputObjectType>();
 
    constructor(collections: EntityCollection[], driver: DataDriver) {
        this.collections = collections;
        this.driver = driver;
    }
 
    /**
     * Generate complete GraphQL schema using existing DataDriver
     */
    generateSchema(): GraphQLSchema {
        // Create all types first
        this.collections.forEach(collection => {
            this.createEntityType(collection);
            this.createInputType(collection);
        });
 
        const queryType = this.createQueryType();
        const mutationType = this.createMutationType();
 
        return new GraphQLSchema({
            query: queryType,
            mutation: mutationType,
        });
    }
 
    /**
     * Create GraphQL type for an entity collection
     */
    private createEntityType(collection: EntityCollection): GraphQLObjectType {
        const typeName = this.getTypeName(collection);
 
        Iif (this.typeRegistry.has(typeName)) {
            return this.typeRegistry.get(typeName)!;
        }
 
        const fields: Record<string, GraphQLFieldConfig<any, any>> = {};
 
        // Add ID field
        fields.id = {
            type: new GraphQLNonNull(GraphQLString),
            description: "Unique identifier",
            resolve: (source) => source.id
        };
 
        // Convert properties to GraphQL fields
        Object.entries(collection.properties).forEach(([key, property]) => {
            if (property.type !== "relation" && key !== "id") {
                const fieldConfig = this.convertPropertyToField(property);
                fieldConfig.resolve = (source) => source.values?.[key];
                fields[key] = fieldConfig;
            }
        });
 
        const entityType = new GraphQLObjectType({
            name: typeName,
            description: collection.description || `${collection.singularName} entity`,
            fields: () => fields
        });
 
        this.typeRegistry.set(typeName, entityType);
        return entityType;
    }
 
    private convertPropertyToField(property: Property): GraphQLFieldConfig<any, any> {
        let type;
 
        switch (property.type) {
            case "string":
                type = GraphQLString;
                break;
            case "number":
                type = GraphQLFloat;
                break;
            case "boolean":
                type = GraphQLBoolean;
                break;
            case "date":
                type = GraphQLString;
                break;
            case "array":
                type = new GraphQLList(GraphQLString);
                break;
            default:
                type = GraphQLString;
        }
 
        return {
            type: property.validation?.required ? new GraphQLNonNull(type) : type,
            description: property.name || property.description
        };
    }
 
    private createInputType(collection: EntityCollection): GraphQLInputObjectType {
        const typeName = `${this.getTypeName(collection)}Input`;
 
        Iif (this.inputTypeRegistry.has(typeName)) {
            return this.inputTypeRegistry.get(typeName)!;
        }
 
        const fields: Record<string, any> = {};
 
        Object.entries(collection.properties).forEach(([key, property]) => {
            if (property.type !== "relation") {
                fields[key] = {
                    type: this.convertPropertyToInputType(property)
                };
            }
        });
 
        const inputType = new GraphQLInputObjectType({
            name: typeName,
            description: `Input for creating/updating ${collection.singularName}`,
            fields
        });
 
        this.inputTypeRegistry.set(typeName, inputType);
        return inputType;
    }
 
    private convertPropertyToInputType(property: Property) {
        switch (property.type) {
            case "string":
                return GraphQLString;
            case "number":
                return GraphQLFloat;
            case "boolean":
                return GraphQLBoolean;
            case "date":
                return GraphQLString;
            case "array":
                return new GraphQLList(GraphQLString);
            default:
                return GraphQLString;
        }
    }
 
    /**
     * Create Query type using existing DataDriver methods
     */
    private createQueryType(): GraphQLObjectType {
        const fields: Record<string, GraphQLFieldConfig<any, any>> = {};
 
        this.collections.forEach(collection => {
            const typeName = this.getTypeName(collection);
            const entityType = this.typeRegistry.get(typeName);
 
            Iif (!entityType) return;
 
            // Single entity query - uses existing fetchEntity
            fields[this.getSingleQueryName(collection)] = {
                type: entityType,
                args: {
                    id: { type: new GraphQLNonNull(GraphQLString) }
                },
                resolve: async (_, args, context: { driver: DataDriver }) => {
                    const ds = context.driver || this.driver;
                    const entity = await ds.fetchEntity({
                        path: collection.dbPath || collection.slug,
                        entityId: args.id,
                        collection
                    });
                    return entity;
                }
            };
 
            // List query - uses existing fetchCollection
            fields[this.getListQueryName(collection)] = {
                type: new GraphQLList(entityType),
                args: {
                    limit: { type: GraphQLInt, defaultValue: 20 },
                    offset: { type: GraphQLInt, defaultValue: 0 },
                    where: { type: GraphQLString },
                    orderBy: { type: GraphQLString }
                },
                resolve: async (_, args, context: { driver: DataDriver }) => {
                    const ds = context.driver || this.driver;
                    let filter: FetchCollectionProps["filter"] | undefined;
                    Iif (args.where) {
                        try {
                            const parsed = JSON.parse(args.where);
                            Iif (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
                                throw new Error("Filter must be a JSON object");
                            }
                            filter = parsed;
                        } catch (e) {
                            throw new Error(`Invalid 'where' filter: ${e instanceof Error ? e.message : "malformed JSON"}`);
                        }
                    }
                    const entities = await ds.fetchCollection({
                        path: collection.dbPath || collection.slug,
                        collection,
                        filter,
                        limit: args.limit,
                        startAfter: args.offset ? String(args.offset) : undefined
                    });
                    return entities;
                }
            };
        });
 
        return new GraphQLObjectType({
            name: "Query",
            fields
        });
    }
 
    /**
     * Create Mutation type using existing DataDriver methods
     */
    private createMutationType(): GraphQLObjectType {
        const fields: Record<string, GraphQLFieldConfig<any, any>> = {};
 
        this.collections.forEach(collection => {
            const typeName = this.getTypeName(collection);
            const entityType = this.typeRegistry.get(typeName);
            const inputType = this.inputTypeRegistry.get(`${typeName}Input`);
 
            Iif (!entityType || !inputType) return;
 
            // Create mutation - uses existing saveEntity
            fields[`create${typeName}`] = {
                type: entityType,
                args: {
                    input: { type: new GraphQLNonNull(inputType) }
                },
                resolve: async (_, args, context: { driver: DataDriver }) => {
                    const ds = context.driver || this.driver;
                    const path = collection.dbPath || collection.slug;
                    const entity = await ds.saveEntity({
                        path,
                        values: args.input,
                        collection,
                        status: "new"
                    });
                    return entity;
                }
            };
 
            // Update mutation - uses existing saveEntity
            fields[`update${typeName}`] = {
                type: entityType,
                args: {
                    id: { type: new GraphQLNonNull(GraphQLString) },
                    input: { type: new GraphQLNonNull(inputType) }
                },
                resolve: async (_, args, context: { driver: DataDriver }) => {
                    const ds = context.driver || this.driver;
                    const entity = await ds.saveEntity({
                        path: collection.dbPath || collection.slug,
                        entityId: args.id,
                        values: args.input,
                        collection,
                        status: "existing"
                    });
                    return entity;
                }
            };
 
            // Delete mutation - uses existing deleteEntity
            fields[`delete${typeName}`] = {
                type: GraphQLBoolean,
                args: {
                    id: { type: new GraphQLNonNull(GraphQLString) }
                },
                resolve: async (_, args, context: { driver: DataDriver }) => {
                    try {
                        const ds = context.driver || this.driver;
                        const existingEntity = await ds.fetchEntity({
                            path: collection.dbPath || collection.slug,
                            entityId: args.id,
                            collection
                        });
                        Iif (!existingEntity) return false;
                        await ds.deleteEntity({
                            entity: existingEntity,
                            collection
                        });
                        return true;
                    } catch {
                        return false;
                    }
                }
            };
        });
 
        return new GraphQLObjectType({
            name: "Mutation",
            fields
        });
    }
 
    // Helper methods
    private getTypeName(collection: EntityCollection): string {
        return collection.singularName?.replace(/\s+/g, "") ||
            collection.name.slice(0, -1).replace(/\s+/g, "");
    }
 
    private getSingleQueryName(collection: EntityCollection): string {
        return this.getTypeName(collection).toLowerCase();
    }
 
    private getListQueryName(collection: EntityCollection): string {
        return collection.slug;
    }
}