type-fest#JsonObject TypeScript Examples

The following examples show how to use type-fest#JsonObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: entity.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
private async validateFieldProperties(
    dataType: EnumDataType,
    properties: JsonObject
  ): Promise<SchemaValidationResult> {
    try {
      const data = properties;
      const schema = getSchemaForDataType(dataType);
      const schemaValidation = await this.jsonSchemaValidationService.validateSchema(
        schema,
        data
      );

      //if schema is not valid - return false, otherwise continue with ret of the checks
      if (!schemaValidation.isValid) {
        return schemaValidation;
      }

      switch (dataType) {
        case EnumDataType.Lookup:
          //check if the actual selected entity exist and can be referenced by this field
          break;

        case (EnumDataType.OptionSet, EnumDataType.MultiSelectOptionSet):
          //check if the actual selected option set exist and can be referenced by this field
          break;

        //todo: add other data type specific checks
        default:
          break;
      }

      return schemaValidation;
    } catch (error) {
      return new SchemaValidationResult(false, error);
    }
  }
Example #2
Source File: jsonHelper.ts    From amplication with Apache License 2.0 6 votes vote down vote up
static read: (path: string) => Promise<JsonObject> = (
    path: string
  ): Promise<any> => {
    return new Promise<any>((resolve, reject) => {
      readFile(path, (err: NodeJS.ErrnoException | null, data: Buffer) => {
        if (err) {
          reject(err);
        } else {
          try {
            resolve(JSON.parse(data.toString()));
          } catch (e) {
            reject(e);
          }
        }
      });
    });
  };
Example #3
Source File: jsonHelper.ts    From amplication with Apache License 2.0 6 votes vote down vote up
static write: (
    path: string,
    packageJson: JsonObject,
    space?: string | number
  ) => Promise<boolean> = (
    path: string,
    packageJson: JsonObject,
    space: string | number = 2
  ) => {
    return new Promise<boolean>((resolve, reject) => {
      const data = new Uint8Array(
        Buffer.from(JSON.stringify(packageJson, null, space))
      );
      writeFile(path, data, err => {
        if (err) {
          reject(err);
        }
        resolve(true);
      });
    });
  };
Example #4
Source File: ControllerRequestHandler.ts    From ZenTS with MIT License 6 votes vote down vote up
protected handleResult(result: ControllerMethodReturnType): void {
    if (!result) {
      return
    }

    if (this.context.req.httpMethod === 'post' && !this.context.res.isStatuscodeSetManual) {
      this.context.res.setStatusCode(201)
    }

    if (result instanceof TemplateResponse) {
      return this.context.res.html(result.html).send()
    } else if (isObject(result)) {
      return this.context.res.json(result as JsonObject).send()
    } else if (Array.isArray(result)) {
      return this.context.res.json(result).send()
    } else if (typeof result === 'string') {
      return this.context.res.text(result).send()
    } else {
      return this.context.error.internal(
        'Controller returned an unsupported value. Please return an object, an array or a string.',
      )
    }
  }
Example #5
Source File: block.service.spec.ts    From amplication with Apache License 2.0 5 votes vote down vote up
EXAMPLE_BLOCK_INPUT: JsonObject & BlockInputOutput = {
  name: 'BlockInput'
}
Example #6
Source File: block.service.ts    From amplication with Apache License 2.0 5 votes vote down vote up
private versionToIBlock<T>(
    version: PrismaBlockVersion & {
      block: PrismaBlock & { parentBlock: PrismaBlock };
      settings: unknown;
    }
  ): T {
    const {
      id,
      createdAt,
      updatedAt,
      parentBlock,
      displayName,
      description,
      blockType,
      lockedAt,
      lockedByUserId
    } = version.block;
    const block: IBlock = {
      id,
      createdAt,
      updatedAt,
      parentBlock,
      displayName,
      description,
      blockType,
      lockedAt,
      lockedByUserId,
      versionNumber: version.versionNumber,
      inputParameters: ((version.inputParameters as unknown) as {
        params: BlockInputOutput[];
      }).params,
      outputParameters: ((version.outputParameters as unknown) as {
        params: BlockInputOutput[];
      }).params
    };
    const settings = version.settings as JsonObject;
    return ({
      ...block,
      ...settings
    } as unknown) as T;
  }
Example #7
Source File: BlockCreateInput.ts    From amplication with Apache License 2.0 5 votes vote down vote up
@InputType({
  isAbstract: true,
  description: undefined
})
export abstract class BlockCreateInput implements JsonObject {
  [key: string]: JsonValue;

  @Field(() => String, {
    nullable: false,
    description: undefined
  })
  displayName!: string;

  @Field(() => String, {
    nullable: true,
    description: undefined
  })
  description?: string;

  @Field(() => WhereParentIdInput, {
    nullable: false,
    description: undefined
  })
  app!: WhereParentIdInput & JsonValue;

  @Field(() => WhereParentIdInput, {
    nullable: true,
    description: undefined
  })
  parentBlock?: WhereParentIdInput & JsonValue;

  @Field(() => [BlockInputOutput], {
    nullable: true,
    description: undefined
  })
  inputParameters?: BlockInputOutput[] & JsonArray;

  @Field(() => [BlockInputOutput], {
    nullable: true,
    description: undefined
  })
  outputParameters?: BlockInputOutput[] & JsonArray;
}
Example #8
Source File: CreateGeneratedAppDTO.ts    From amplication with Apache License 2.0 5 votes vote down vote up
export class CreateGeneratedAppDTO implements JsonObject {
  [key: string]: JsonValue;
  @IsNotEmpty()
  @IsString()
  buildId: string;
}
Example #9
Source File: CreateDeploymentDTO.ts    From amplication with Apache License 2.0 5 votes vote down vote up
export class CreateDeploymentDTO implements JsonObject {
  [key: string]: JsonValue;
  @IsNotEmpty()
  @IsString()
  deploymentId: string;
}
Example #10
Source File: constants.ts    From amplication with Apache License 2.0 5 votes vote down vote up
DATA_TYPE_TO_DEFAULT_PROPERTIES: {
  [key in EnumDataType]: JsonObject;
} = {
  [EnumDataType.SingleLineText]: {
    maxLength: 1000
  },
  [EnumDataType.MultiLineText]: {
    maxLength: 1000
  },
  [EnumDataType.Email]: {},
  [EnumDataType.WholeNumber]: {
    minimumValue: -999999999,
    maximumValue: 999999999
  },
  [EnumDataType.DecimalNumber]: {
    minimumValue: -999999999,
    maximumValue: 999999999,
    precision: 2
  },
  [EnumDataType.DateTime]: {
    timeZone: 'localTime',
    dateOnly: false
  },
  [EnumDataType.Lookup]: {
    relatedEntityId: '',
    allowMultipleSelection: false,
    relatedFieldId: ''
  },
  [EnumDataType.Boolean]: {},
  [EnumDataType.Json]: {},
  [EnumDataType.OptionSet]: {
    options: [{ label: 'Option 1', value: 'Option1' }]
  },
  [EnumDataType.MultiSelectOptionSet]: {
    options: [{ label: 'Option 1', value: 'Option1' }]
  },
  [EnumDataType.GeographicLocation]: {},
  [EnumDataType.CreatedAt]: {},
  [EnumDataType.UpdatedAt]: {},
  [EnumDataType.Id]: {},
  [EnumDataType.Username]: {},
  [EnumDataType.Password]: {},
  [EnumDataType.Roles]: {}
}
Example #11
Source File: EntityFieldCreateInput.ts    From amplication with Apache License 2.0 5 votes vote down vote up
@Field(() => GraphQLJSONObject, {
    nullable: false,
    description: undefined
  })
  properties!: JsonObject;
Example #12
Source File: EntityFieldUpdateInput.ts    From amplication with Apache License 2.0 5 votes vote down vote up
@Field(() => GraphQLJSONObject, {
    nullable: true,
    description: undefined
  })
  properties?: JsonObject | null;
Example #13
Source File: entity.service.ts    From amplication with Apache License 2.0 5 votes vote down vote up
/** 2021-02-10
   * This method is used to fix previous versions of lookup fields
   * that are missing the property.relatedEntityField value The function will
   * throw an exception if the provided field already have a related entity
   * field, or it is a field of a different type other the Lookup
   */
  async createDefaultRelatedField(
    args: CreateDefaultRelatedFieldArgs,
    user: User
  ): Promise<EntityField> {
    // Get field to update
    const field = await this.getField({
      where: args.where,
      include: { entityVersion: true }
    });

    if (field.dataType != EnumDataType.Lookup) {
      throw new ConflictException(
        `Cannot created default related field, because the provided field is not of a relation field`
      );
    }

    if (
      !isEmpty(((field.properties as unknown) as types.Lookup).relatedFieldId)
    ) {
      throw new ConflictException(
        `Cannot created default related field, because the provided field is already related to another field`
      );
    }

    return await this.useLocking(
      field.entityVersion.entityId,
      user,
      async entity => {
        // Validate args
        this.validateFieldMutationArgs(
          {
            ...args,
            data: {
              properties: field.properties as JsonObject,
              dataType: field.dataType
            }
          },
          entity
        );

        const relatedFieldId = cuid();

        // Cast the received properties as Lookup properties
        const properties = (field.properties as unknown) as types.Lookup;

        //create the related field
        await this.createRelatedField(
          relatedFieldId,
          args.relatedFieldName,
          args.relatedFieldDisplayName,
          !properties.allowMultipleSelection,
          properties.relatedEntityId,
          entity.id,
          field.permanentId,
          user
        );

        properties.relatedFieldId = relatedFieldId;

        //Update the field with the ID of the related field
        return this.prisma.entityField.update({
          where: {
            id: field.id
          },
          data: {
            properties: (properties as unknown) as Prisma.InputJsonValue
          }
        });
      }
    );
  }
Example #14
Source File: jsonHelper.ts    From amplication with Apache License 2.0 5 votes vote down vote up
private packageJson: Promise<JsonObject>;
Example #15
Source File: Context.ts    From ZenTS with MIT License 5 votes vote down vote up
public async build(
    request: IncomingMessage,
    response: ServerResponse,
    params: IncomingParams,
    route: Route,
  ): Promise<void> {
    if (this.isBuild) {
      return
    }

    this.isBuild = true

    const method = request.method.toLowerCase()
    let body: ParsedBody = null

    if (method === 'post' || method === 'put') {
      const bodyParser = new BodyParser()

      body = await bodyParser.parse(request)
    }

    if (typeof route.validationSchema !== 'undefined') {
      const validationResult = route.validationSchema.validate(body.fields)

      if (validationResult.error) {
        this.isReqBodyValid = false
        this.requestBodyValidationErrors = validationResult.error.details.map((error) => {
          return {
            message: error.message,
            path: error.path,
          }
        })
      } else {
        body.fields = validationResult.value as JsonObject
      }
    }

    const cookie = config.web?.cookie?.enable ? new Cookie(request.headers) : null
    const req = new Request(request, body, params)
    const res = new Response(response, req, cookie)
    const error = new ResponseError(res)

    this.container = {
      body,
      cookie,
      req,
      res,
      error,
    }
  }
Example #16
Source File: entity.service.ts    From amplication with Apache License 2.0 4 votes vote down vote up
/**
   * Created the field input with the relevant properties. When dataType is not provided, it will be guessed based on the field name
   * @param args
   * @param entity
   * @returns
   */
  async createFieldCreateInputByDisplayName(
    args: CreateOneEntityFieldByDisplayNameArgs,
    entity: Entity
  ): Promise<{ name: string; dataType: EnumDataType; properties: JsonObject }> {
    const { displayName } = args.data;
    const lowerCaseName = displayName.toLowerCase();
    const name = camelCase(displayName);

    let dataType: EnumDataType | null = null;

    if (args.data.dataType) {
      dataType = args.data.dataType as EnumDataType;
    } else if (lowerCaseName.includes('date')) {
      dataType = EnumDataType.DateTime;
    } else if (
      lowerCaseName.includes('description') ||
      lowerCaseName.includes('comments')
    ) {
      dataType = EnumDataType.MultiLineText;
    } else if (lowerCaseName.includes('email')) {
      dataType = EnumDataType.Email;
    } else if (lowerCaseName.includes('status')) {
      dataType = EnumDataType.OptionSet;
    } else if (lowerCaseName.startsWith('is')) {
      dataType = EnumDataType.Boolean;
    } else if (lowerCaseName.includes('price')) {
      dataType = EnumDataType.DecimalNumber;
    } else if (
      lowerCaseName.includes('quantity') ||
      lowerCaseName.includes('qty')
    ) {
      dataType = EnumDataType.WholeNumber;
    }

    if (dataType === EnumDataType.Lookup || dataType === null) {
      // Find an entity with the field's display name
      const relatedEntity = await this.findEntityByNames(name, entity.appId);
      // If found attempt to create a lookup field
      if (relatedEntity) {
        // The created field would be multiple selection if its name is equal to
        // the related entity's plural display name
        const allowMultipleSelection =
          relatedEntity.pluralDisplayName.toLowerCase() === lowerCaseName;

        // The related field allow multiple selection should be the opposite of
        // the field's
        const relatedFieldAllowMultipleSelection = !allowMultipleSelection;

        // The related field name should resemble the name of the field's entity
        const relatedFieldName = camelCase(
          relatedFieldAllowMultipleSelection
            ? entity.name
            : entity.pluralDisplayName
        );

        // If there are no existing fields with the desired name, instruct to create a lookup field
        if (
          await this.isFieldNameAvailable(relatedFieldName, relatedEntity.id)
        ) {
          return {
            name,
            dataType: EnumDataType.Lookup,
            properties: {
              relatedEntityId: relatedEntity.id,
              allowMultipleSelection
            }
          };
        }
      }
    }

    return {
      name,
      dataType: dataType || EnumDataType.SingleLineText,
      properties:
        DATA_TYPE_TO_DEFAULT_PROPERTIES[dataType || EnumDataType.SingleLineText]
    };
  }