| 43 | CodegenRegistry.registerExternal(CompatibleScalarConverter); |
| 44 | |
| 45 | export class Gen { |
| 46 | static external = CodegenRegistry.getExternal(); |
| 47 | |
| 48 | constructor(private typeResolver: TypeResolver, private regOptions: { [key: string]: any } = {}) { |
| 49 | |
| 50 | } |
| 51 | |
| 52 | private generate(typeInfo: TypeInfo) { |
| 53 | const InnerGeneratorClass = CodegenRegistry.get(typeInfo.typeId); |
| 54 | if (!InnerGeneratorClass) { |
| 55 | throw new Error(`${typeInfo.typeId} generator not exists`); |
| 56 | } |
| 57 | const scope = new Scope(); |
| 58 | const generator = new InnerGeneratorClass(typeInfo, new CodecBuilder(scope, this.typeResolver), scope); |
| 59 | |
| 60 | const funcString = generator.toSerializer(); |
| 61 | if (this.typeResolver.config && this.typeResolver.config.hooks) { |
| 62 | const afterCodeGenerated = this.typeResolver.config.hooks.afterCodeGenerated; |
| 63 | if (typeof afterCodeGenerated === "function") { |
| 64 | return new Function(afterCodeGenerated(funcString)); |
| 65 | } |
| 66 | } |
| 67 | return new Function(funcString); |
| 68 | } |
| 69 | |
| 70 | private register(typeInfo: TypeInfo, serializer?: Serializer) { |
| 71 | this.typeResolver.registerSerializer(typeInfo, serializer); |
| 72 | } |
| 73 | |
| 74 | private isRegistered(typeInfo: TypeInfo) { |
| 75 | return !!this.typeResolver.getSerializerByTypeInfo(typeInfo); |
| 76 | } |
| 77 | |
| 78 | private isFullyGenerated(typeInfo: TypeInfo) { |
| 79 | const ser = this.typeResolver.getSerializerByTypeInfo(typeInfo); |
| 80 | return ser && ser._initialized; |
| 81 | } |
| 82 | |
| 83 | private traversalContainer(typeInfo: TypeInfo) { |
| 84 | if (TypeId.userDefinedType(typeInfo.typeId)) { |
| 85 | if (this.isFullyGenerated(typeInfo)) { |
| 86 | return; |
| 87 | } |
| 88 | const options = (typeInfo).options; |
| 89 | const unionType = typeInfo.typeId === TypeId.UNION |
| 90 | || typeInfo.typeId === TypeId.TYPED_UNION |
| 91 | || typeInfo.typeId === TypeId.NAMED_UNION; |
| 92 | if (unionType && options?.cases && Object.keys(options.cases).length > 0) { |
| 93 | this.register(typeInfo); |
| 94 | Object.values(options.cases).forEach((x) => { |
| 95 | this.traversalContainer(x); |
| 96 | }); |
| 97 | const func = this.generate(typeInfo); |
| 98 | this.register(typeInfo, func()(this.typeResolver, Gen.external, typeInfo, this.regOptions)); |
| 99 | return; |
| 100 | } else if (options?.props && Object.keys(options.props).length > 0) { |
| 101 | this.register(typeInfo); |
| 102 | Object.values(options.props).forEach((x) => { |
nothing calls this directly
no test coverage detected