|
| 1 | +import mkdirp from 'mkdirp'; |
| 2 | +import handlebars from 'handlebars'; |
| 3 | +import fs from 'fs'; |
| 4 | + |
| 5 | +export default class TypescriptInterfaceGenerator { |
| 6 | + templates = {}; |
| 7 | + |
| 8 | + constructor() { |
| 9 | + const templatePath = `${__dirname}/../../templates/typescript`; |
| 10 | + this.template = handlebars.compile(fs.readFileSync(`${templatePath}/interface.ts`).toString()) |
| 11 | + } |
| 12 | + |
| 13 | + help() { |
| 14 | + } |
| 15 | + |
| 16 | + generate(api, resource, dir) { |
| 17 | + const fields = this.parseFields(resource) |
| 18 | + const name = resource.title |
| 19 | + let dest = `${dir}/interfaces` |
| 20 | + |
| 21 | + try { |
| 22 | + mkdirp.sync(dest); |
| 23 | + } catch(e) { |
| 24 | + // nothing |
| 25 | + } |
| 26 | + |
| 27 | + dest += `/${name.toLowerCase()}.ts`; |
| 28 | + |
| 29 | + fs.writeFileSync(dest, this.template({fields, name})); |
| 30 | + } |
| 31 | + |
| 32 | + getType(field) { |
| 33 | + if (field.reference) { |
| 34 | + return field.reference.title; |
| 35 | + } |
| 36 | + |
| 37 | + switch (field.range) { |
| 38 | + case 'http://www.w3.org/2001/XMLSchema#integer': |
| 39 | + case 'http://www.w3.org/2001/XMLSchema#decimal': |
| 40 | + return 'number'; |
| 41 | + case 'http://www.w3.org/2001/XMLSchema#boolean': |
| 42 | + return 'bool'; |
| 43 | + case 'http://www.w3.org/2001/XMLSchema#date': |
| 44 | + case 'http://www.w3.org/2001/XMLSchema#dateTime': |
| 45 | + case 'http://www.w3.org/2001/XMLSchema#time': |
| 46 | + return 'Date'; |
| 47 | + case 'http://www.w3.org/2001/XMLSchema#string': |
| 48 | + return 'string'; |
| 49 | + } |
| 50 | + |
| 51 | + return 'any'; |
| 52 | + } |
| 53 | + |
| 54 | + getDescription(field) { |
| 55 | + return field.description ? field.description.replace(/"/g, "'") : '' |
| 56 | + } |
| 57 | + |
| 58 | + parseFields(resource) { |
| 59 | + const fields = {} |
| 60 | + |
| 61 | + for (let field of resource.writableFields) { |
| 62 | + fields[field.name] = { |
| 63 | + notrequired: !field.required, |
| 64 | + name: field.name, |
| 65 | + type: this.getType(field), |
| 66 | + description: this.getDescription(field), |
| 67 | + readonly: false |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + for (let field of resource.readableFields) { |
| 72 | + if (fields[field.name] !== undefined) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + fields[field.name] = { |
| 77 | + notrequired: !field.required, |
| 78 | + name: field.name, |
| 79 | + type: this.getType(field), |
| 80 | + description: this.getDescription(field), |
| 81 | + readonly: true |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return Object.keys(fields).map((e) => fields[e]); |
| 86 | + } |
| 87 | + |
| 88 | + // createFile(template, dest, context) { |
| 89 | + // } |
| 90 | +} |
0 commit comments