Created
May 27, 2021 17:30
-
-
Save ThePlenkov/2fc31e05a43a4ec395c9a4d8f6c8276a to your computer and use it in GitHub Desktop.
Convert generated with hana-cli CDS to another one with renamed fields ( like all to snake|camel|kebab case )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cds from "@sap/cds"; | |
import {struct} from "@sap/cds/apis/csn"; | |
import fs from "fs/promises"; | |
import {toSnakeCase} from "js-convert-case"; | |
import {Command} from "commander"; | |
const program = new Command(); | |
interface Options { | |
schema: string; | |
namespace: string; | |
prefix: string; | |
case: string; | |
} | |
program | |
.option("-s, --schema <schema>", "imported CDS") | |
.option("-n, --namespace <namespace>", "imported namespace") | |
.option("-p, --prefix <prefix>", "new namespace") | |
.option("-c, --case <case>", "case to use: camel|snake|kebab") | |
.parse(process.argv); | |
class Main { | |
static async formatCDS(options: Options) { | |
let {schema, namespace, prefix} = options; | |
const csn = await cds.load(schema); | |
let model = `using {${namespace}} from './${schema.replace( | |
".cds", | |
"" | |
)}';\n`; | |
Object.keys(csn.definitions) | |
.filter((key) => key.startsWith(`${namespace}.`)) | |
.forEach((key) => { | |
let entity = csn.definitions[key] as struct; | |
switch (entity.kind) { | |
case "entity": | |
model += `entity ${prefix}.${key} as projection on ${key} {\n`; | |
Object.keys(entity.elements).forEach((element, index, array) => { | |
// to be extended with more cases if needed | |
let alias = | |
options.case === "snake" ? toSnakeCase(element) : element; | |
//tab | |
model += "\t"; | |
// element or alias | |
model += element === alias ? element : `${element} as ${alias}`; | |
// no comma for last element | |
index === array.length || (model += ","); | |
// line brake | |
model += "\n"; | |
}); | |
model += "};\n"; | |
break; | |
default: | |
break; | |
} | |
}); | |
fs.writeFile(`${prefix}.cds`, model); | |
} | |
} | |
//console.log(program.opts()); | |
Main.formatCDS(program.opts() as Options); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I left a comment over there as well about the using. I committed to the feature branch a solution that puts multiple using statements - one for each entity. This approach looks pretty nasty but does work without namespaces. I also implemented a few other case types - camel, upper, lower, pacal, and dot (although syntactically in CAP CDS that probably doesn't make sense). Maybe have a look at this branch and see if that works for your use case.