UNPKG

ccd-ng2

Version:

Class based web framework on top of Express that uses async await operators to simplify the controllers logic and promote writing clean, simple and maintainable web server

72 lines (70 loc) 2.53 kB
"use strict"; const ccd_1 = require('ccd'); const path = require('path'); const fs = require('fs'); const mkdirp = require('mkdirp'); exports.NG_SVC_GROUP_NAME = 'ngServices'; class NgServiceCreatorDescriptor { constructor(targetName, outputDir, name, excludeSuffix = 'Ctrl', skipMethods = []) { this.targetName = targetName; this.outputDir = outputDir; this.name = name; this.excludeSuffix = excludeSuffix; this.skipMethods = skipMethods; } apply(ctrl) { console.log(`Creating NG service for ${this.targetName}`); console.log('Methods:'); let group = ctrl.__descriptors.get(ccd_1.VERBS_GROUP_NAME); let filename = this.name; if (!filename) { filename = this.targetName; } mkdirp.sync(this.outputDir); const filepath = path.join(this.outputDir, filename + '.ts'); const fileContents = this.getTemplate(this.targetName, group); fs.writeFileSync(filepath, fileContents); } getTemplate(name, group) { return (`import { Injectable } from '@angular/core'; import { SimpleRestService } from 'ccNgRest'; import { DescriptorGroup } from './descriptorStore';; @Injectable() export class ${name}Svc{ constructor(private rest: SimpleRestService){ } ${group.descriptors.map(this.createServiceMethod.bind(this)).join('\n')} }`); } createServiceMethod(desc) { let hasPayload = desc.verb === 'post' || desc.verb === 'put'; let resource = desc.resource; let methodArgs = ''; let args = `'${resource}'`; if (resource.indexOf(':id') > 0) { methodArgs += 'id'; args = args.replace(':id', '') + '+id'; } if (hasPayload) { methodArgs += ', payload'; args += ', payload'; } return (` ${desc.targetName}(${methodArgs}){ return this.rest.${desc.verb}(${args}); }`); } } function ngSvcGen(outputDir, apply = true, name = null, excludeSuffix = 'Ctrl', skipMethods = []) { return function (constructor) { if (!apply) return constructor; let ctrl = constructor.prototype; ccd_1.ensureDescriptorStore(ctrl); let docDescriptor = new NgServiceCreatorDescriptor(constructor.name, outputDir); ctrl.__descriptors.addTo(exports.NG_SVC_GROUP_NAME, ccd_1.InvokeOrder.LAST, docDescriptor); return constructor; }; } exports.ngSvcGen = ngSvcGen; //# sourceMappingURL=ccd-ng2.js.map