fork of hey-api/openapi-ts because I need some additional things
at feat/skip-token 59 lines 1.6 kB view raw
1import type { AnalysisContext, NodeName } from '@hey-api/codegen-core'; 2 3import { py } from '../../ts-python'; 4import type { MaybePyDsl } from '../base'; 5import { PyDsl } from '../base'; 6 7const Mixed = PyDsl<py.MemberExpression>; 8 9export class AttrPyDsl extends Mixed { 10 readonly '~dsl' = 'AttrPyDsl'; 11 12 protected object?: MaybePyDsl<py.Expression>; 13 protected prop?: NodeName; 14 15 constructor(object: MaybePyDsl<py.Expression>, prop: NodeName) { 16 super(); 17 this.object = object; 18 this.name.set(prop); 19 } 20 21 static attr(object: MaybePyDsl<py.Expression>, prop: NodeName): AttrPyDsl { 22 return new AttrPyDsl(object, prop); 23 } 24 25 override analyze(ctx: AnalysisContext): void { 26 super.analyze(ctx); 27 ctx.analyze(this.object); 28 ctx.analyze(this.name); 29 } 30 31 /** Returns true when all required builder calls are present. */ 32 get isValid(): boolean { 33 return this.missingRequiredCalls().length === 0; 34 } 35 36 override toAst(): py.MemberExpression { 37 this.$validate(); 38 39 return py.factory.createMemberExpression( 40 this.$node(this.object!) as py.Expression, 41 py.factory.createIdentifier(this.name.toString()), 42 ); 43 } 44 45 $validate(): asserts this is this & { 46 object: MaybePyDsl<py.Expression>; 47 } { 48 const missing = this.missingRequiredCalls(); 49 if (missing.length === 0) return; 50 throw new Error(`Attribute access missing ${missing.join(' and ')}`); 51 } 52 53 private missingRequiredCalls(): ReadonlyArray<string> { 54 const missing: Array<string> = []; 55 if (!this.object) missing.push('object'); 56 if (!this.name.toString()) missing.push('property name'); 57 return missing; 58 } 59}