Last active
May 30, 2019 07:54
-
-
Save phenomnomnominal/5f22ba6221ff541514a36c4f56248524 to your computer and use it in GitHub Desktop.
Third version of our transform, which creates the new AST nodes for the getter and setter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dependencies: | |
// ... | |
import { tstemplate } from '@phenomnomnominal/tstemplate'; | |
// Constants: | |
// ... | |
const RESULT_QUERY = 'PropertyDeclaration, GetAccessor, SetAccessor'; | |
const GETTER_SETTER_TEMPLATE = tstemplate.compile(` | |
class Template { | |
private <%= privateName %>: <%= type %>; | |
public get <%= name %> (): <%= type %> { | |
let val = this.<%= privateName %> | |
return val; | |
} | |
public set <%= name %> (value: <%= type %>) { | |
let val = value; | |
this.<%= privateName %> = val; | |
} | |
} | |
`); | |
export function transformer (source: SourceFile): TransformerFactory<Node> { | |
// ... | |
} | |
export function valueDecoratorToGetterAndSetterFactory (nodes: Array<Node>): TransformerFactory<Node> { | |
return function (context: TransformationContext): Transformer<Node> { | |
// ... | |
function visit (node: Node): Node | Array<Node> { | |
if (nodes.includes(node)) { | |
// Create the base structure of the new getter/setter: | |
const property = node as PropertyDeclaration; | |
const propertyName = property.name.getText(); | |
const [internal, getter, setter] = tsquery(GETTER_SETTER_TEMPLATE({ | |
name: property.name, | |
privateName: createIdentifier(`_${propertyName}`), | |
type: property.type! || createToken(SyntaxKind.AnyKeyword) | |
}), RESULT_QUERY); | |
// Return the new AST nodes to replace the old one: | |
return [internal, getter, setter]; | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment