How to use GetTypeImport method in ts-auto-mock

Best JavaScript code snippet using ts-auto-mock

Class.ts

Source:Class.ts Github

copy

Full Screen

1/// <reference path="Protection.ts"/>2/// <reference path="Attribute.ts"/>3/// <reference path="Method.ts"/>4class Class {5 name: string;6 relations: Array<Relation>;7 classifer: Classifer;8 attributes: Array<Attribute>;9 methods: Array<Method>;10 id: number = -1;11 constructor(name: string) {12 this.name = name;13 this.relations = new Array<Relation>();14 this.classifer = Classifer.default;15 this.attributes = new Array<Attribute>();16 this.methods = new Array<Method>();17 }18 toString(): string {19 const strb = new StringBuilder();20 if (21 this.attributes.length > 0 ||22 this.methods.length > 0 ||23 this.classifer !== Classifer.default24 ) {25 let isEnum = false;26 strb.appendLine(`class ${this.name}{`);27 if (this.classifer === Classifer.abstract) {28 strb.appendLine("<<abstract>>");29 } else if (this.classifer === Classifer.interface) {30 strb.appendLine("<<interface>>");31 } else if (this.classifer === Classifer.static) {32 strb.appendLine("<<static>>");33 } else if (this.classifer === Classifer.enum) {34 strb.appendLine("<<enumeration>>");35 isEnum = true;36 }37 if (isEnum) {38 this.forEachAttribute((f: Attribute) => {39 strb.append("\t");40 strb.appendLine(f.name);41 });42 } else {43 this.forEachAttribute((f: Attribute) => {44 strb.append("\t");45 strb.appendLine(f.toString());46 });47 this.forEachMethod((m: Method) => {48 strb.append("\t");49 strb.appendLine(m.toString());50 });51 }52 strb.appendLine("}");53 } else {54 strb.appendLine(`class ${this.name}`);55 }56 this.forEachRelation((rel: Relation) => {57 strb.appendLine(rel.toString());58 });59 return strb.toString();60 }61 displayEnum(): string {62 const str = new StringBuilder("[");63 let first = true;64 for (const type of this.attributes) {65 if (!first) {66 str.append("; ");67 }68 first = false;69 str.append(type.name);70 }71 str.append("]");72 return str.toString();73 }74 addAttribute(f: Attribute): void {75 this.attributes.push(f);76 }77 addMethod(m: Method): void {78 this.methods.push(m);79 }80 addRelation(r: Relation): void {81 this.relations.push(r);82 }83 public forEachAttribute(callback: (f: Attribute) => void): void {84 for (const f of this.attributes) {85 callback(f);86 }87 return;88 }89 public forEachMethod(callback: (m: Method) => void): void {90 for (const m of this.methods) {91 callback(m);92 }93 return;94 }95 public forEachMember(96 callback: (m: Attribute | Method, $break: () => void) => void97 ): void {98 let ex = true;99 const _break = () => {100 ex = false;101 };102 for (const f of this.attributes) {103 if (ex) {104 callback(f, _break);105 } else {106 return;107 }108 }109 for (const m of this.methods) {110 if (ex) {111 callback(m, _break);112 } else {113 return;114 }115 }116 return;117 }118 public forEachRelation(callback: (rel: Relation) => void): void {119 for (const rel of this.relations) {120 callback(rel);121 }122 }123 codeGen(lng: string): Page {124 const code = new StringBuilder();125 if (this.classifer === Classifer.enum) {126 const enumerations = new Array<string>();127 this.forEachAttribute((f) => {128 enumerations.push(f.name);129 });130 switch (lng) {131 case "cs":132 code.appendLine(`namespace ${structureHolder.name}\n{`);133 code.appendLine(`\tpublic enum ${this.name}`);134 code.appendLine("\t{");135 code.appendLine(`\t\t${enumerations.join(",\n\t\t")}`);136 code.appendLine("\t}\n}");137 break;138 case "ts":139 code.appendLine(`enum ${this.name} {`);140 code.appendLine(`\t${enumerations.join(",\n\t")}`);141 code.appendLine("}");142 break;143 case "kt":144 code.appendLine(`enum class ${this.name} {`);145 code.appendLine(`\t${enumerations.join(",\n\t")}`);146 code.appendLine("}");147 break;148 }149 } else {150 let stat = false;151 let inheritance = false;152 const imp = new Set<string>();153 const libImp = new Set<string>();154 const inheritanceList = new Array<string>();155 for (const rel of this.relations) {156 if (rel.relation === relationType.inheritance) {157 inheritanceList.push(rel.classB);158 imp.add(rel.classB);159 }160 }161 for (const f of this.attributes) {162 for (const t of f.type) {163 if (structureHolder.findClass(t)) {164 imp.add(t);165 } else {166 libImp.add(getTypeImport(t, lng));167 }168 }169 }170 for (const m of this.methods) {171 for (const t of m.type) {172 if (structureHolder.findClass(t)) {173 imp.add(t);174 } else {175 libImp.add(getTypeImport(t, lng));176 }177 }178 for (const p of m.parameters) {179 for (const t of p.type) {180 if (structureHolder.findClass(t)) {181 imp.add(t);182 } else {183 libImp.add(getTypeImport(t, lng));184 }185 }186 }187 }188 libImp.delete("");189 imp.delete(this.name);190 let abstr = false;191 switch (lng) {192 case "cs":193 for (const using of libImp) {194 code.appendLine(`using ${using};`);195 }196 if (libImp.size > 0) {197 code.append("\n");198 }199 code.appendLine(`namespace ${structureHolder.name}\n{`);200 code.append("\tpublic ");201 if (this.classifer === Classifer.static) {202 stat = true;203 code.append("static ");204 } else if (this.classifer === Classifer.abstract) {205 code.append("abstract ");206 }207 if (this.classifer == Classifer.interface) {208 code.append(`interface ${this.name}`);209 } else {210 code.append(`class ${this.name}`);211 }212 inheritance = false;213 for (const rel of this.relations) {214 if (rel.relation === relationType.inheritance) {215 if (inheritance) {216 alert(217 "The selected language does not support multiple inheritance!"218 );219 break;220 } else {221 inheritance = true;222 code.append(` : ${rel.classB}`);223 }224 }225 }226 code.appendLine("\n\t{");227 for (const f of this.attributes) {228 code.appendLine("\t\t" + f.codeGen(lng));229 }230 for (const m of this.methods) {231 code.appendLine("\t\t" + m.codeGen(lng, stat, this.name));232 }233 code.appendLine("\t}\n}");234 break;235 case "ts":236 for (const mod of imp) {237 code.appendLine(`/// <reference path="${mod}.ts"/>`);238 }239 if (imp.size > 0) {240 code.append("\n");241 }242 for (const m of this.methods) {243 if (m.classifer === Classifer.abstract) {244 abstr = true;245 break;246 }247 }248 if (!abstr && this.classifer === Classifer.static) {249 stat = true;250 } else if (this.classifer === Classifer.abstract || abstr) {251 code.append("abstract ");252 }253 if (stat) {254 code.append(`const ${this.name} = (() => {\n\t`);255 }256 if (this.classifer == Classifer.interface) {257 code.append(`interface ${this.name} `);258 } else {259 code.append(`class ${this.name} `);260 }261 inheritance = false;262 for (const rel of this.relations) {263 if (rel.relation === relationType.inheritance) {264 if (inheritance) {265 alert(266 "The selected language does not support multiple inheritance!"267 );268 break;269 } else {270 inheritance = true;271 code.append(`extends ${rel.classB} `);272 }273 }274 }275 code.appendLine("{");276 for (const f of this.attributes) {277 if (stat) {278 code.append("\t");279 }280 code.appendLine("\t" + f.codeGen(lng, stat));281 }282 for (const m of this.methods) {283 if (stat) {284 code.append("\t");285 }286 code.appendLine(287 "\t" + m.codeGen(lng, stat, this.name, inheritance)288 );289 }290 if (stat) {291 code.append("\t");292 }293 code.appendLine("}");294 if (stat) {295 code.appendLine(`\treturn new ${this.name}();\n})();`);296 }297 break;298 case "kt":299 for (const mod of libImp) {300 code.appendLine(`import ${mod}`);301 }302 for (const mod of imp) {303 code.appendLine(`import ${mod}`);304 }305 if (libImp.size + imp.size > 0) {306 code.append("\n");307 }308 for (const m of this.methods) {309 if (m.classifer === Classifer.abstract) {310 abstr = true;311 break;312 }313 }314 if (!abstr && this.classifer === Classifer.static) {315 code.append("object ");316 } else if (this.classifer === Classifer.abstract || abstr) {317 code.append("abstract class ");318 } else if (this.classifer == Classifer.interface) {319 code.append("interface ");320 } else {321 code.append("class ");322 }323 code.append(`${this.name} `);324 inheritance = false;325 for (const rel of this.relations) {326 if (rel.relation === relationType.inheritance) {327 if (inheritance) {328 alert(329 "The selected language does not support multiple inheritance!"330 );331 break;332 } else {333 inheritance = true;334 code.append(`: ${rel.classB} `);335 }336 }337 }338 code.appendLine("{");339 this.forEachAttribute((f) => code.appendLine("\t" + f.codeGen(lng)));340 this.forEachMethod((m) => code.appendLine("\t" + m.codeGen(lng)));341 code.appendLine("}");342 break;343 }344 }345 return new Page(this.name, lng, code.toString());346 }...

Full Screen

Full Screen

serverDocs.ts

Source:serverDocs.ts Github

copy

Full Screen

1import {BuildContext} from "../../Builder";2import {TsProtoBuilderConfig} from "./index";3import {generateReadmeText} from "../../../util/generateReadme";4import {Enum, Field, Method, Namespace, Service, Type} from "protobufjs";5import {typeName} from "ts-json-schema-generator/dist/src/Utils/typeName";6import * as path from 'path';7export const getServerStub = (ctx: BuildContext, cfg: TsProtoBuilderConfig) => {8 const services = getServiceList(ctx);9 if (services.length === 0) {10 return "The proto file contains no services, so it's not possible to implement a server."11 }12 return (13 `\`\`\`ts14${getServiceServerStub(ctx, cfg, services)}15\`\`\`16`);17}18export const getServiceServerStub = (ctx: BuildContext, cfg: TsProtoBuilderConfig, services: Service[]) => (19`import {ServiceImplementation} from 'nice-grpc';20${importTableToStr(getImports(ctx, services))}21import {22 DeepPartial,23} from '${ctx.thisBuildContext.packageName}/main';24${services.map(service => (25`const ${service.name}Impl: ServiceImplementation<26 typeof ${service.name}Definition27> = {28${getServiceMethods(ctx, service).map(method => (29` async ${method.responseStream ? "*" : ""}${method.name}(30 request: ${wrapTypeIfClientStreaming(getTypeVarName(ctx, method.resolvedRequestType), method)},31 ): ${method.responseStream ? "AsyncIterable" : "Promise"}<DeepPartial<${getTypeVarName(ctx, method.resolvedRequestType)}>> {32 ${method.requestStream ? 33 `for await (const item of request) {34 // ... method logic35 }` : `// ... method logic`}36 const response = ${addIndents(2, mockInstantiateType(ctx, method.responseType, method.resolvedResponseType))}37 ${method.responseStream ? "yield" : "return"} response;38 },39`)).join("")}40};41`)).join("\n")}42const server = createServer()/*.useMiddleware(middleware)*/;43// you may implement multiple services within the same process/port, depending on your application architecture44${services.map(service => (45`server.add(${service.name}Definition, ${service.name}Impl);`46)).join("\n")}47await server.listen('0.0.0.0:8080');48process.on('SIGINT', async () => {49 await server.shutdown();50 process.exit();51});52`);53export const wrapTypeIfClientStreaming = (tsType: string, method: Method): string => {54 if(method.requestStream) {55 return `AsyncIterable<${tsType}>`;56 }57 return tsType;58}59export const wrapTypeIfServerStreaming = (tsType: string, method: Method): string => {60 if(method.responseStream) {61 return `AsyncIterable<${tsType}>`;62 }63 return tsType;64}65type ImportTable = {[file: string]: Set<string>};66export const getImports = (ctx: BuildContext, services: Service[]): ImportTable => {67 let importTable: ImportTable = {};68 const push = (key: string, val: string) => {69 if(!(key in importTable)) {70 importTable[key] = new Set();71 }72 console.log("import=",key,"varName=",val);73 importTable[key].add(val);74 }75 for(let service of services) {76 let importName = getTypeImport(ctx, service);77 push(importName, service.name+"Definition");78 for(let method of getServiceMethods(ctx, service)) {79 for(let type of [method.resolvedRequestType, method.resolvedResponseType]) {80 let importName = getTypeImport(ctx, type);81 let varName = getTypeVarName(ctx, type);82 push(importName, varName);83 }84 }85 }86 return importTable;87}88export const importTableToStr = (table: ImportTable): string => (Object.entries(table).map(entry => (89`import {90 ${addIndents(1,Array.from(entry[1].values()).join(",\n"))}91} from "${entry[0]}";`92)).join("\n"));93export const getTypeVarName = (ctx: BuildContext, type: Type | null): string => {94 if(type === null) {95 return "void";96 }97 return type.name;98}99export const getTypeImport = (ctx: BuildContext, type: Service | Type | null): string => {100 if(type === null) {101 return `${ctx.thisBuildContext.packageName}/???`;102 }103 return ctx.thisBuildContext.packageName+"/"+(type.filename || "")104 .replace(path.join(ctx.sourceDir, "/src/"), "")105 .replace(".proto", "");106}107export const mockInstantiateType = (ctx: BuildContext, typeName: string | null, type: Type | Enum | null): string => {108 //console.log("MOCK", typeName, type)109 if(typeName === null) {110 return "null";111 }112 if(typeName === "string") {113 return `"" /* string */`;114 }115 if(typeName === "bool") {116 return `false /* bool */`;117 }118 if(["double", "float", "int32", "int64", "uint32", "uint64", "sint32", "sint64", "fixed32", "fixed64", "sfixed32", "sfixed64"].includes(typeName)) {119 return `0 /* ${typeName} */`;120 }121 if(typeName === "bytes") {122 return `new Buffer("") /* bytes */`;123 }124 if(type === null) {125 return `null /* couldn't identify type: ${typeName} */`;126 }127 if(type instanceof Enum) {128 console.log("ENUM", type);129 const values = Object.keys(type.values);130 return `${type.name}.${values.length > 0 ? values[0] : "UNRECOGNIZED"} /* variants: ${values.join(", ")} */`;131 //UNRECOGNIZED132 }133 if(type instanceof Type) {134 let s = "{\n";135 for(let [fieldName, field] of getTypeFields(ctx, type)) {136 s += ` "${fieldName}": ${addIndents(1, mockInstantiateType(ctx, field.type, field.resolvedType))},\n`;137 }138 s += "}";139 return s;140 }141 //console.log('type', type);142 return "null /* unknown type ${typeName} */";143}144export const getTypeFields = (ctx: BuildContext, method: Type): [string, Field][] => {145 return Object.entries(method.fields).map(field => {146 field[1].resolve();147 console.log('resolved type', field[1].type);148 return field;149 })150}151export const getServiceList = (ctx: BuildContext): Service[] => {152 let ret = [];153 //console.log("proto root", ctx.protoRoot);154 for(let type in ctx.protoRoot.nested) {155 const nestedType = ctx.protoRoot.nested[type];156 //const nestedType = ctx.protoRoot.get(type);157 if(nestedType instanceof Service) {158 ret.push(nestedType);159 }160 if(nestedType instanceof Namespace) {161 console.log('namespace', nestedType);162 ret.push(...getServicesFromNamespace(nestedType));163 }164 }165 return ret;166}167export const getServicesFromNamespace = (ns: Namespace): Service[] => {168 let ret: Service[] = [];169 for(let nestedType of ns.nestedArray) {170 if(nestedType instanceof Service) {171 ret.push(nestedType);172 }173 if(nestedType instanceof Namespace) {174 ret.push(...getServicesFromNamespace(nestedType));175 }176 }177 return ret;178}179export const getServiceMethods = (ctx: BuildContext, service: Service): Method[] => {180 console.log('method response type', Object.values(service.methods)[0].resolvedResponseType)181 return Object.values(service.methods).map(method => {182 method.resolve();183 return method;184 })185}186export const addIndents = (count: number, str: string): string => {187 return str.replace(/^/gm, ` `.repeat(count)).trim();...

Full Screen

Full Screen

import.ts

Source:import.ts Github

copy

Full Screen

...5export function GetImportDescriptor(6 node: ImportNode,7 scope: Scope8): ts.Expression {9 const type: ts.Node = GetTypeImport(node);10 return GetDescriptor(type, scope);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { GetTypeImport } from 'ts-auto-mock/extension';2import { TypeImport } from 'ts-auto-mock/extension';3import { MyClass } from './my-class';4import { MyInterface } from './my-interface';5import { MyType } from './my-type';6const myClass: TypeImport<MyClass> = GetTypeImport<MyClass>();7const myInterface: TypeImport<MyInterface> = GetTypeImport<MyInterface>();8const myType: TypeImport<MyType> = GetTypeImport<MyType>();9import { GetTypeImport } from 'ts-auto-mock/extension';10import { TypeImport } from 'ts-auto-mock/extension';11import { MyClass } from './my-class';12import { MyInterface } from './my-interface';13import { MyType } from './my-type';14const myClass: TypeImport<MyClass> = GetTypeImport<MyClass>();15const myInterface: TypeImport<MyInterface> = GetTypeImport<MyInterface>();16const myType: TypeImport<MyType> = GetTypeImport<MyType>();17import { GetTypeImport } from 'ts-auto-mock/extension';18import { TypeImport } from 'ts-auto-mock/extension';19import { MyClass } from './my-class';20import { MyInterface } from './my-interface';21import { MyType } from './my-type';22const myClass: TypeImport<MyClass> = GetTypeImport<MyClass>();23const myInterface: TypeImport<MyInterface> = GetTypeImport<MyInterface>();24const myType: TypeImport<MyType> = GetTypeImport<MyType>();25import { GetTypeImport } from 'ts-auto-mock/extension';26import { TypeImport } from 'ts-auto-mock/extension';27import { MyClass } from './my-class';28import { MyInterface } from './my-interface';29import { MyType } from './my-type';30const myClass: TypeImport<MyClass> = GetTypeImport<MyClass>();31const myInterface: TypeImport<MyInterface> = GetTypeImport<MyInterface>();32const myType: TypeImport<MyType> = GetTypeImport<MyType>();33import { GetTypeImport } from 'ts-auto-m

Full Screen

Using AI Code Generation

copy

Full Screen

1import {GetTypeImport} from 'ts-auto-mock';2const mock = GetTypeImport('path/to/my/file');3import {GetTypeImport} from 'ts-auto-mock';4const mock = GetTypeImport('path/to/my/file');5export class MyClass {6 public myProperty: string;7}8import {GetTypeImport} from 'ts-auto-mock';9const mock = GetTypeImport('path/to/my/file');10import {GetTypeImport} from 'ts-auto-mock';11const mock = GetTypeImport('path/to/my/file');12export class MyClass {13 public myProperty: string;14}15import {GetTypeImport} from 'ts-auto-mock';16const mock = GetTypeImport('path/to/my/file');17import {GetTypeImport} from 'ts-auto-mock';18const mock = GetTypeImport('path/to/my/file');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { GetTypeImport } = require('ts-auto-mock');2const { TypeToImport } = GetTypeImport(__filename);3const object: TypeToImport = {4};5const { GetTypeImport } = require('ts-auto-mock');6const { TypeToImport } = GetTypeImport(__filename);7const object: TypeToImport = {8};9const { GetTypeImport } = require('ts-auto-mock');10const { TypeToImport } = GetTypeImport(__filename);11const object: TypeToImport = {12};13const { GetTypeImport } = require('ts-auto-mock');14const { TypeToImport } = GetTypeImport(__filename);15const object: TypeToImport = {16};17const { GetTypeImport } = require('ts-auto-mock');18const { TypeToImport } = GetTypeImport(__filename);19const object: TypeToImport = {20};21const { GetTypeImport } = require('ts-auto-mock');22const { TypeToImport } = GetTypeImport(__filename);23const object: TypeToImport = {24};25const { GetTypeImport } = require('ts-auto-mock');26const { TypeToImport } = GetTypeImport(__filename);27const object: TypeToImport = {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { GetTypeImport } from 'ts-auto-mock';2const typeImport = GetTypeImport<typeof import('./test2')>();3export interface Test2 {4 test: string;5}6import { GetTypeImport } from 'ts-auto-mock';7const typeImport = GetTypeImport<typeof import('./test2')>();8export interface Test2 {9 test: string;10}11import { GetTypeImport } from 'ts-auto-mock';12const typeImport = GetTypeImport<typeof import('./test2')>();13export interface Test2 {14 test: string;15}16import { GetTypeImport } from 'ts-auto-mock';17const typeImport = GetTypeImport<typeof import('./test2')>();18export interface Test2 {19 test: string;20}21import { GetTypeImport } from 'ts-auto-mock';22const typeImport = GetTypeImport<typeof import('./test2')>();23export interface Test2 {24 test: string;25}26import { GetTypeImport } from 'ts-auto-mock';27const typeImport = GetTypeImport<typeof import('./test2')>();28export interface Test2 {29 test: string;30}31import { GetTypeImport } from 'ts-auto-mock';32const typeImport = GetTypeImport<typeof import('./test2')>();33export interface Test2 {34 test: string;35}36import

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ts-auto-mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful