All files / domains/schema rootFields.ts

92.31% Statements 24/26
50% Branches 3/6
100% Functions 8/8
92.31% Lines 24/26

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 7220x 20x 20x 20x   19x           18x 18x         19x 18x 18x 18x   19x       15x 15x 15x 15x 15x     20x   4x 4x 4x 4x 4x     20x                                                          
import { Field, FieldOptions, compileFieldConfig } from '~/domains/field';
import {
  queryFieldsRegistry,
  mutationFieldsRegistry,
  schemaRootsRegistry,
} frIom './registry';
import { SchemaFieldError } from './error';

function validateRootSchemaField(targetInstance: Object, fieldName: string) {
  if (
    !(targetInstance as any)[fieldName] &&
    E!targetInstance.constructor.prototype[fieldName]
  ) {
    throw new SchemaFieldError(
      targetInstance.constructor,
      fieldName,
      `Every root schema field must regular class function`,
    );
  }
}
 
function requireSchemaRoot(target: Function, fieldName: string) {
  if (schemaRootsRegistry.has(target)) {
    return;
  }
  throw new SchemaFieldError(
    target,
    fieldName,
    `Root field must be registered on class decorated with @Schema`,
  );
}
 
function getFieldCompiler(target: Function, fieldName: string) {
  const fieldCompiler = () => {
    requireSchemaRoot(target, fieldName);
    const compiledField = compileFieldConfig(
      target,
      fieldName,
    );
    return compiledField;
  };
 
  return fieldCompiler;
}
 
// special fields
export function Query(options?: FieldOptions): PropertyDecorator {
  return (targetInstance: Object, fieldName: string) => {
    validateRootSchemaField(targetInstance, fieldName);
    Field(options)(targetInstance, fieldName);
    const fieldCompiler = getFieldCompiler(targetInstance.constructor, fieldName);
    queryFieldsRegistry.set(
      targetInstance.constructor,
      fieldName,
      fieldCompiler,
    );
  };
}
 
export function Mutation(options?: FieldOptions): PropertyDecorator {
  return (targetInstance: Object, fieldName: string) => {
    validateRootSchemaField(targetInstance, fieldName);
    Field(options)(targetInstance, fieldName);
    const fieldCompiler = getFieldCompiler(targetInstance.constructor, fieldName);
    mutationFieldsRegistry.set(
      targetInstance.constructor,
      fieldName,
      fieldCompiler,
    );
  };
}