@krlwlfrt/xsdco
Version:
XSD converter
64 lines (55 loc) • 2.09 kB
text/typescript
/*
* Copyright (C) 2019, 2020 Karl-Philipp Wulfert
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {isAttribute, Property, ThingWithNameAndNamespace} from '@krlwlfrt/tsg';
/**
* Get a valid name
* @param name Name to make a valid name from
* @returns Valid name
*/
function getValidName(name: string): string {
return name
.split('.')
.join('__');
}
/**
* Generate name for a thing
* @param thing Thing to generate name for
* @returns Name for a thing
*/
export function generateName(thing: ThingWithNameAndNamespace): string {
if (isAttribute(thing)) {
return thing.name;
}
return getValidName(`${thing.namespace === '' ? '' : thing.namespace + '__'}${thing.name}`);
}
/**
* Create a property type generator with fixed root namespaces
* @param rootNamespaces List of namespaces to consider as root(s)
* @returns A function that creates a name for a property
*/
export function generatePropertyTypeFactory(rootNamespaces: string[]): (property: Property) => string {
return (property: Property): string => {
if (['date', 'time'].indexOf(property.type.name) >= 0) {
return 'string';
}
if (['decimal', 'short', 'unsignedByte', 'int', 'integer'].includes(property.type.name)) {
return 'number';
}
if (typeof property.type.namespace === 'string' && rootNamespaces.indexOf(property.type.namespace) >= 0) {
return property.type.name;
}
return getValidName(`${property.type.namespace === '' ? '' : property.type.namespace + '__'}${property.type.name}`);
};
}