ts-morph#ImportDeclarationStructure TypeScript Examples
The following examples show how to use
ts-morph#ImportDeclarationStructure.
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: ModelsGenerator.ts From gengen with MIT License | 6 votes |
private getImports(): ImportDeclarationStructure[] {
return [
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './Guid',
namedImports: [{ name: 'Guid' }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './date-converters',
namedImports: [{ name: 'toDateIn' }, { name: 'toDateOut' }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './types',
namespaceImport: TYPES_NAMESPACE,
isTypeOnly: true
}
];
}
Example #2
Source File: generator.ts From wsdl-tsclient with MIT License | 6 votes |
/**
* To avoid duplicated imports
*/
function addSafeImport(
imports: OptionalKind<ImportDeclarationStructure>[],
moduleSpecifier: string,
namedImport: string
) {
if (!imports.find((imp) => imp.moduleSpecifier == moduleSpecifier)) {
imports.push({
moduleSpecifier,
namedImports: [{ name: namedImport }],
});
}
}
Example #3
Source File: import-declaration-map.ts From prisma-nestjs-graphql with MIT License | 6 votes |
add(name: string, value: OptionalKind<ImportDeclarationStructure> | string): void {
if (!this.has(name)) {
const structure: OptionalKind<ImportDeclarationStructure> =
typeof value === 'string'
? { moduleSpecifier: value, namedImports: [{ name }] }
: value;
this.set(name, structure);
}
}
Example #4
Source File: import-declaration-map.ts From prisma-nestjs-graphql with MIT License | 6 votes |
*toStatements(): Iterable<ImportDeclarationStructure> {
const iterator = this.values();
let result = iterator.next();
while (result.value) {
yield {
...result.value,
kind: StructureKind.ImportDeclaration,
};
result = iterator.next();
}
}
Example #5
Source File: AngularServicesGenerator.ts From gengen with MIT License | 5 votes |
protected getImports(): ImportDeclarationStructure[] {
return [
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: '@angular/common/http',
namedImports: [{ name: HTTP_CLIENT }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: '@angular/core',
namedImports: [{ name: 'Injectable' }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: 'rxjs',
namedImports: [{ name: 'Observable' }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './Guid',
namedImports: [{ name: 'Guid' }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './base-http.service',
namedImports: this.settings.withRequestOptions
? [{ name: BASE_SERVICE }, { name: HTTP_REQUEST_OPTIONS }]
: [{ name: BASE_SERVICE }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './download.service',
namedImports: [{ name: DOWNLOAD_SERVICE }, { name: 'IDownloadResult' }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './utils',
namedImports: [{ name: GET_BASE_PATH_FUNCTION_NAME }]
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './mappers',
namespaceImport: MAPPERS_NAMESPACE
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: './types',
namespaceImport: TYPES_NAMESPACE,
isTypeOnly: true
},
{
kind: StructureKind.ImportDeclaration,
moduleSpecifier: `./${this.aliasResolver.getModelsModuleName()}`,
namespaceImport: MODELS_NAMESPACE
}
];
}
Example #6
Source File: generator.ts From wsdl-tsclient with MIT License | 5 votes |
function generateDefinitionFile(
project: Project,
definition: null | Definition,
defDir: string,
stack: string[],
generated: Definition[],
options: GeneratorOptions
): void {
const defName = definition.name;
const defFilePath = path.join(defDir, `${defName}.ts`);
const defFile = project.createSourceFile(defFilePath, "", {
overwrite: true,
});
generated.push(definition);
const definitionImports: OptionalKind<ImportDeclarationStructure>[] = [];
const definitionProperties: PropertySignatureStructure[] = [];
for (const prop of definition.properties) {
if (options.modelPropertyNaming) {
switch (options.modelPropertyNaming) {
case ModelPropertyNaming.camelCase:
prop.name = camelcase(prop.name);
break;
case ModelPropertyNaming.PascalCase:
prop.name = camelcase(prop.name, { pascalCase: true });
break;
}
}
if (prop.kind === "PRIMITIVE") {
// e.g. string
definitionProperties.push(createProperty(prop.name, prop.type, prop.description, prop.isArray));
} else if (prop.kind === "REFERENCE") {
// e.g. Items
if (!generated.includes(prop.ref)) {
// Wasn't generated yet
generateDefinitionFile(project, prop.ref, defDir, [...stack, prop.ref.name], generated, options);
}
// If a property is of the same type as its parent type, don't add import
if (prop.ref.name !== definition.name) {
addSafeImport(definitionImports, `./${prop.ref.name}`, prop.ref.name);
}
definitionProperties.push(createProperty(prop.name, prop.ref.name, prop.sourceName, prop.isArray));
}
}
defFile.addImportDeclarations(definitionImports);
defFile.addStatements([
{
leadingTrivia: (writer) => writer.newLine(),
isExported: true,
name: defName,
docs: [definition.docs.join("\n")],
kind: StructureKind.Interface,
properties: definitionProperties,
},
]);
Logger.log(`Writing Definition file: ${path.resolve(path.join(defDir, defName))}.ts`);
defFile.saveSync();
}
Example #7
Source File: import-declaration-map.ts From prisma-nestjs-graphql with MIT License | 5 votes |
add(name: string, value: OptionalKind<ImportDeclarationStructure>): void;
Example #8
Source File: import-declaration-map.ts From prisma-nestjs-graphql with MIT License | 5 votes |
export class ImportDeclarationMap extends Map<
string,
OptionalKind<ImportDeclarationStructure>
> {
add(name: string, moduleSpecifier: string): void;
add(name: string, value: OptionalKind<ImportDeclarationStructure>): void;
add(name: string, value: OptionalKind<ImportDeclarationStructure> | string): void {
if (!this.has(name)) {
const structure: OptionalKind<ImportDeclarationStructure> =
typeof value === 'string'
? { moduleSpecifier: value, namedImports: [{ name }] }
: value;
this.set(name, structure);
}
}
create(args: {
name: string;
from: string;
defaultImport?: string | true;
namespaceImport?: string;
namedImport?: boolean;
}) {
const { from, defaultImport, namespaceImport, namedImport } = args;
let name = args.name;
const value = {
moduleSpecifier: from,
namedImports: [] as OptionalKind<ImportSpecifierStructure>[],
defaultImport: undefined as string | undefined,
namespaceImport: undefined as string | undefined,
};
if (namedImport === true && namespaceImport) {
value.namedImports = [{ name: namespaceImport }];
name = namespaceImport;
} else if (defaultImport) {
value.defaultImport = defaultImport === true ? name : defaultImport;
name = value.defaultImport;
} else if (namespaceImport) {
value.namespaceImport = namespaceImport;
name = namespaceImport;
} else {
value.namedImports = [{ name }];
}
this.add(name, value);
}
*toStatements(): Iterable<ImportDeclarationStructure> {
const iterator = this.values();
let result = iterator.next();
while (result.value) {
yield {
...result.value,
kind: StructureKind.ImportDeclaration,
};
result = iterator.next();
}
}
}
Example #9
Source File: generate.spec.ts From prisma-nestjs-graphql with MIT License | 5 votes |
importDeclarations: ImportDeclarationStructure[] = []
Example #10
Source File: test.spec.ts From prisma-nestjs-graphql with MIT License | 5 votes |
importDeclarations: ImportDeclarationStructure[] = []
Example #11
Source File: generator.ts From wsdl-tsclient with MIT License | 4 votes |
export async function generate(
parsedWsdl: ParsedWsdl,
outDir: string,
options: Partial<GeneratorOptions>
): Promise<void> {
const mergedOptions: GeneratorOptions = {
...defaultOptions,
...options,
};
const project = new Project();
const portsDir = path.join(outDir, "ports");
const servicesDir = path.join(outDir, "services");
const defDir = path.join(outDir, "definitions");
const allMethods: Method[] = [];
const allDefinitions: Definition[] = [];
const clientImports: Array<OptionalKind<ImportDeclarationStructure>> = [];
const clientServices: Array<OptionalKind<PropertySignatureStructure>> = [];
for (const service of parsedWsdl.services) {
const serviceFilePath = path.join(servicesDir, `${service.name}.ts`);
const serviceFile = project.createSourceFile(serviceFilePath, "", {
overwrite: true,
});
const serviceImports: Array<OptionalKind<ImportDeclarationStructure>> = [];
const servicePorts: Array<OptionalKind<PropertySignatureStructure>> = [];
for (const port of parsedWsdl.ports) {
const portFilePath = path.join(portsDir, `${port.name}.ts`);
const portFile = project.createSourceFile(portFilePath, "", {
overwrite: true,
});
const portImports: Array<OptionalKind<ImportDeclarationStructure>> = [];
const portFileMethods: Array<OptionalKind<MethodSignatureStructure>> = [];
for (const method of port.methods) {
// TODO: Deduplicate PortImports
if (method.paramDefinition !== null) {
if (!allDefinitions.includes(method.paramDefinition)) {
// Definition is not generated
generateDefinitionFile(
project,
method.paramDefinition,
defDir,
[method.paramDefinition.name],
allDefinitions,
mergedOptions
);
addSafeImport(
clientImports,
`./definitions/${method.paramDefinition.name}`,
method.paramDefinition.name
);
}
addSafeImport(
portImports,
`../definitions/${method.paramDefinition.name}`,
method.paramDefinition.name
);
}
if (method.returnDefinition !== null) {
if (!allDefinitions.includes(method.returnDefinition)) {
// Definition is not generated
generateDefinitionFile(
project,
method.returnDefinition,
defDir,
[method.returnDefinition.name],
allDefinitions,
mergedOptions
);
addSafeImport(
clientImports,
`./definitions/${method.returnDefinition.name}`,
method.returnDefinition.name
);
}
addSafeImport(
portImports,
`../definitions/${method.returnDefinition.name}`,
method.returnDefinition.name
);
}
// TODO: Deduplicate PortMethods
allMethods.push(method);
portFileMethods.push({
name: sanitizePropName(method.name),
parameters: [
{
name: camelcase(method.paramName),
type: method.paramDefinition ? method.paramDefinition.name : "{}",
},
{
name: "callback",
type: `(err: any, result: ${
method.returnDefinition ? method.returnDefinition.name : "unknown"
}, rawResponse: any, soapHeader: any, rawRequest: any) => void`, // TODO: Use ts-morph to generate proper type
},
],
returnType: "void",
});
} // End of PortMethod
if (!mergedOptions.emitDefinitionsOnly) {
addSafeImport(serviceImports, `../ports/${port.name}`, port.name);
servicePorts.push({
name: sanitizePropName(port.name),
isReadonly: true,
type: port.name,
});
portFile.addImportDeclarations(portImports);
portFile.addStatements([
{
leadingTrivia: (writer) => writer.newLine(),
isExported: true,
kind: StructureKind.Interface,
name: port.name,
methods: portFileMethods,
},
]);
Logger.log(`Writing Port file: ${path.resolve(path.join(portsDir, port.name))}.ts`);
portFile.saveSync();
}
} // End of Port
if (!mergedOptions.emitDefinitionsOnly) {
addSafeImport(clientImports, `./services/${service.name}`, service.name);
clientServices.push({ name: sanitizePropName(service.name), type: service.name });
serviceFile.addImportDeclarations(serviceImports);
serviceFile.addStatements([
{
leadingTrivia: (writer) => writer.newLine(),
isExported: true,
kind: StructureKind.Interface,
name: service.name,
properties: servicePorts,
},
]);
Logger.log(`Writing Service file: ${path.resolve(path.join(servicesDir, service.name))}.ts`);
serviceFile.saveSync();
}
} // End of Service
if (!mergedOptions.emitDefinitionsOnly) {
const clientFilePath = path.join(outDir, "client.ts");
const clientFile = project.createSourceFile(clientFilePath, "", {
overwrite: true,
});
clientFile.addImportDeclaration({
moduleSpecifier: "soap",
namedImports: [
{ name: "Client", alias: "SoapClient" },
{ name: "createClientAsync", alias: "soapCreateClientAsync" },
],
});
clientFile.addImportDeclarations(clientImports);
clientFile.addStatements([
{
leadingTrivia: (writer) => writer.newLine(),
isExported: true,
kind: StructureKind.Interface,
// docs: [`${parsedWsdl.name}Client`],
name: `${parsedWsdl.name}Client`,
properties: clientServices,
extends: ["SoapClient"],
methods: allMethods.map<OptionalKind<MethodSignatureStructure>>((method) => ({
name: sanitizePropName(`${method.name}Async`),
parameters: [
{
name: camelcase(method.paramName),
type: method.paramDefinition ? method.paramDefinition.name : "{}",
},
],
returnType: `Promise<[result: ${
method.returnDefinition ? method.returnDefinition.name : "unknown"
}, rawResponse: any, soapHeader: any, rawRequest: any]>`,
})),
},
]);
const createClientDeclaration = clientFile.addFunction({
name: "createClientAsync",
docs: [`Create ${parsedWsdl.name}Client`],
isExported: true,
parameters: [
{
isRestParameter: true,
name: "args",
type: "Parameters<typeof soapCreateClientAsync>",
},
],
returnType: `Promise<${parsedWsdl.name}Client>`, // TODO: `any` keyword is very dangerous
});
createClientDeclaration.setBodyText("return soapCreateClientAsync(args[0], args[1], args[2]) as any;");
Logger.log(`Writing Client file: ${path.resolve(path.join(outDir, "client"))}.ts`);
clientFile.saveSync();
}
// Create index file with re-exports
const indexFilePath = path.join(outDir, "index.ts");
const indexFile = project.createSourceFile(indexFilePath, "", {
overwrite: true,
});
indexFile.addExportDeclarations(
allDefinitions.map((def) => ({
namedExports: [def.name],
moduleSpecifier: `./definitions/${def.name}`,
}))
);
if (!mergedOptions.emitDefinitionsOnly) {
// TODO: Aggregate all exports during declarations generation
// https://ts-morph.com/details/exports
indexFile.addExportDeclarations([
{
namedExports: ["createClientAsync", `${parsedWsdl.name}Client`],
moduleSpecifier: "./client",
},
]);
indexFile.addExportDeclarations(
parsedWsdl.services.map((service) => ({
namedExports: [service.name],
moduleSpecifier: `./services/${service.name}`,
}))
);
indexFile.addExportDeclarations(
parsedWsdl.ports.map((port) => ({
namedExports: [port.name],
moduleSpecifier: `./ports/${port.name}`,
}))
);
}
Logger.log(`Writing Index file: ${path.resolve(path.join(outDir, "index"))}.ts`);
indexFile.saveSync();
}