protected generateConstructor()

in packages/appsync-modelgen-plugin/src/visitors/appsync-dart-visitor.ts [386:436]


  protected generateConstructor(model: CodeGenModel, declarationBlock: DartDeclarationBlock): void {
    //Model._internal
    const args = this.isNullSafety()
      ? `{${model.fields
          .map(f => `${this.isFieldRequired(f) ? 'required ' : ''}${this.getFieldName(f) === 'id' ? 'this.' : ''}${this.getFieldName(f)}`)
          .join(', ')}}`
      : `{${model.fields.map(f => `${this.isFieldRequired(f) ? '@required ' : ''}this.${this.getFieldName(f)}`).join(', ')}}`;
    const internalFields = model.fields.filter(f => this.getFieldName(f) !== 'id');
    const internalImpl = this.isNullSafety()
      ? internalFields.length
        ? `: ${internalFields.map(f => `_${this.getFieldName(f)} = ${this.getFieldName(f)}`).join(', ')};`
        : ';'
      : ';';
    declarationBlock.addClassMethod(`${this.getModelName(model)}._internal`, '', [{ name: args }], internalImpl, {
      const: true,
      isBlock: false,
    });
    //factory Model
    const writableFields: CodeGenField[] = this.getWritableFields(model);
    const returnParamStr = writableFields
      .map(field => {
        const fieldName = this.getFieldName(field);
        if (fieldName === 'id') {
          return 'id: id == null ? UUID.getUUID() : id';
        } else if (field.isList) {
          return `${fieldName}: ${fieldName} != null ? ${this.getNativeType(field)}.unmodifiable(${fieldName}) : ${fieldName}`;
        } else {
          return `${fieldName}: ${fieldName}`;
        }
      })
      .join(',\n');
    const factoryImpl = [`return ${this.getModelName(model)}._internal(`, indentMultiline(`${returnParamStr});`)].join('\n');
    const factoryParam = this.isNullSafety()
      ? `{${writableFields
          .map(f => {
            if (this.getFieldName(f) === 'id' || !this.isFieldRequired(f)) {
              return `${this.getNativeType(f)}? ${this.getFieldName(f)}`;
            }
            return `required ${this.getNativeType(f)} ${this.getFieldName(f)}`;
          })
          .join(', ')}}`
      : `{${writableFields
          .map(
            f =>
              `${this.getFieldName(f) !== 'id' && this.isFieldRequired(f) ? '@required ' : ''}${this.getNativeType(f)} ${this.getFieldName(
                f,
              )}`,
          )
          .join(', ')}}`;
    declarationBlock.addClassMethod(this.getModelName(model), 'factory', [{ name: factoryParam }], factoryImpl);
  }