@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
91 lines (80 loc) • 3.7 kB
JavaScript
const path = require('path')
const cds = require('../../cds')
const FeatureToggleBuildPlugin = require('./featureToggleBuildPlugin')
const { OUTPUT_MODE, OUTPUT_MODE_RESULT, FLAVOR_LOCALIZED_EDMX } = require('../constants')
const DEBUG = cds.debug('cli|build')
class EdmxBuildPlugin extends FeatureToggleBuildPlugin {
async compileToEdmx(model, edmxDest, compileOptions = {}) { // NOSONAR
const promises = []
// generate edmx for services only that have the odata protocol
const serviceNames = cds.reflect(model).services
.filter(service => this._isOdataProtocol(service))
.map(service => service.name)
// new compile impl is throwing error in case no services exist!
if (serviceNames.length > 0) {
const options = {
...this._options4edmx(),
...compileOptions,
serviceNames
}
DEBUG?.(`compiling edmx files using OData version ${options.version}`)
const result = cds.compile.to.edmx(model, options)
if (result) {
let langs = compileOptions[FLAVOR_LOCALIZED_EDMX] === false ? [] : this.task.options.lang || cds.env.i18n.languages
if (langs.split) { // string to array
langs = langs.split(',')
}
if (langs.length > 0 && langs[0] !== 'all' && langs.indexOf('') < 0) {
langs.push('') // make sure fallback language is in, runtime expects it
}
for (let [content, key] of result) {
const serviceName = key.file ? key.file : key.name
if (this.hasBuildOption(OUTPUT_MODE, OUTPUT_MODE_RESULT)) {
this._result.services.add(serviceName)
}
const locResult = cds.localize(model, langs, content)
if (locResult[Symbol.iterator]) { // multi result
for (let [localizedContent, { lang }] of locResult) {
promises.push(this._writeEdmxForLang(localizedContent, serviceName, lang, edmxDest))
}
} else { // single result
promises.push(this._writeEdmxForLang(locResult, serviceName, langs[0], edmxDest))
}
}
}
}
return Promise.all(promises)
}
_isOdataProtocol(srv) {
let yes = srv._serves_odata; if (yes) return typeof yes === 'function' ? yes.call(srv) : yes // >= cds 7.4.0
let protocols = cds.service.protocols4?.(srv) // >= cds 7.4.0
if (!protocols) { // @sap/cds < 7.3.0
protocols = cds.service.protocols.protocol4(srv)
if (typeof protocols === "string") return protocols.startsWith('odata')
}
return protocols.some(p => p && p.startsWith('odata'))
}
_options4odata() {
const o = this.options()
o.version = cds.env.odata.version
return o
}
_options4edmx() {
const o = this._options4odata()
o.service = 'all'
return o
}
_writeEdmxForLang(content, serviceName, lang, edmxDest) {
const fileName = serviceName + (lang ? '_' + lang + '.xml' : '.xml')
if (this.hasBuildOption(OUTPUT_MODE, OUTPUT_MODE_RESULT)) {
this._result.languages.add(lang)
this._result.edmx.set(fileName, content)
}
//edmxDest might be null
if (edmxDest) {
return this.write(content).to(path.join(edmxDest, fileName))
}
return Promise.resolve()
}
}
module.exports = EdmxBuildPlugin