@sap/cds
Version:
SAP Cloud Application Programming Model - CDS for Node.js
73 lines (63 loc) • 2.2 kB
JavaScript
const { ensureNoDraftsSuffix, ensureUnlocalized } = require('./draft')
const { isDuplicate } = require('./rewriteAsterisks')
const resolveMediaTypeAnnotation = type => {
if (!type) {
return null
}
if (typeof type === 'object' && type.ref && type.ref[0] === '$self') {
return { ref: type.ref.slice(1) }
}
if (typeof type === 'object' && type.ref) {
return { ref: type.ref }
}
if (typeof type === 'object' && type['=']) {
return { ref: [type['='].replaceAll(/\./g, '_')] }
}
return { val: type }
}
const _addColumn = (name, mediaType, columns, url, target) => {
if (mediaType.ref && target.elements[mediaType?.ref?.[0]]?.virtual) return
const col = {
xpr: [
'case',
'when',
{ ref: [name] },
'=',
{ val: null },
'then',
{ val: null },
'else',
{ func: 'coalesce', args: [mediaType, { val: 'application/octet-stream' }] },
'end'
],
as: `${name}@odata.mediaContentType`
}
if (!columns.find(isDuplicate(col))) columns.push(col)
if (url) {
const ref = {
ref: [name],
as: `${name}@odata.mediaReadLink`
}
if (!columns.find(isDuplicate(ref))) columns.push(ref)
}
}
const handleStreamProperties = (target, columns, model) => {
if (!target || !model || !columns) return
let index = columns.length
while (index--) {
const col = columns[index]
const name = col.ref && col.ref[col.ref.length - 1]
const element = name && target.elements[name]
const type = element && element.type
const mediaType = resolveMediaTypeAnnotation(element?.['@Core.MediaType'])
const ignoreMediaType = mediaType && element['@Core.IsURL']
if (col.ref && (type === 'cds.LargeBinary' || (mediaType && !ignoreMediaType))) {
if (mediaType && !element.virtual) _addColumn(name, mediaType, columns, element['@Core.IsURL'], target)
columns.splice(index, 1)
} else if (col.expand && col.ref) {
const tgt = target.elements[col.ref] && target.elements[col.ref].target
tgt && handleStreamProperties(model.definitions[ensureUnlocalized(ensureNoDraftsSuffix(tgt))], col.expand, model)
}
}
}
module.exports = { handleStreamProperties }