draig-car
Version:
Database REST API interactive generator CLI and REPL OpenAPI3 based JS generator with interactive ORM/ODM REPL
70 lines (66 loc) • 2.31 kB
JavaScript
const chalk = require('chalk')
const util = require('util')
const u = require('../util')
const c = require('./common')
const draigAnnotations = {
"delete": () => [ "true", "false" ],
"get": () => [ "true", "false" ],
"model": ctx => Object.keys(ctx.api.components.schemas),
"optional": ctx => Object.keys(ctx.api.components.schemas),
"patch": () => [ "true", "false" ],
"post": () => [ "true", "false" ],
"query": () => [ u.lastquery || 'knex(' ],
"sch-recip": () => [],
"sch-relation": ctx => ctx.model.allRels,
"sch-type-autokey": () => [ "true", "false" ],
"sch-type-default": () => [ "knex.fn.now()" ],
"tableName": ctx => ctx.model.allTabs,
"transform": () => [ u.lasttransform || '_.' ]
}
module.exports.annotateAction = async function annotateAction(args) {
let ctx = this.context
let [value, hashKey, path] = c.apiValue(ctx, args)
if (typeof value === 'undefined' || !util.isObject(value)) {
console.error(
chalk`Sorry, can't create annotation under invalid path entry {green ${args}}`
)
return u.exitOrContinue(this)
}
let key = await c.question(
this,
Object.keys(draigAnnotations),
chalk`Annotation key for {green ${path.join(' ')}} `
)
if(key === "") return u.exitOrContinue(this)
if(!key in Object.keys(draigAnnotations)) {
console.error(
chalk`Invalid annotation key {green ${key}}. `
+`Valid ones are {green ${draigAnnotations.join(", ")}}`
)
return u.exitOrContinue(this)
}
try {
const oldvalue = c.apiGet(ctx.api, [ ...path, `x-draig-${key}` ]) || ''
let newval = await c.question(
this,
[ ...draigAnnotations[key](ctx) ],
chalk`Annotation for {green ${key}} (C-P for oldvalue) `,
oldvalue.replace(/\n/, '')
)
if(newval === '') return u.exitOrContinue(this)
newval = isNaN(Number(newval)) ? newval : Number(newval)
console.log(
chalk`Annotation value: {green ${newval}} (type {green ${typeof newval}})`
)
// Horrible js-yaml hack to force | block in openapi-yaml generation
if(typeof newval === 'string' && ['query','transform'].includes(key))
newval = newval.trim() + '\n'
c.apiSet(ctx.api, [ ...path, `x-draig-${key}` ], newval)
u.saveYaml(ctx.argv.api, ctx.api)
} catch(e) {
console.error(
chalk`Annotation failed: {green ${e}} - Check for valid annotations`
)
}
u.exitOrContinue(this)
}