Vulcan/packages/vulcan-lib/lib/modules/intl.js

75 lines
1.8 KiB
JavaScript
Raw Normal View History

import SimpleSchema from 'simpl-schema';
2018-05-09 09:46:47 +09:00
export const Locales = [];
2018-05-10 17:17:44 +09:00
export const registerLocale = locale => {
2018-05-09 09:46:47 +09:00
Locales.push(locale);
}
/*
Look for type name in a few different places
Note: look into simplifying this
*/
export const isIntlField = fieldSchema => {
const typeProperty = fieldSchema.type;
let type;
if (Array.isArray(typeProperty)) {
type = typeProperty[0].type;
} else {
type = typeProperty.singleType ? typeProperty.singleType : typeProperty.definitions[0].type;
}
return type.name === 'IntlString';
}
/*
Generate custom IntlString SimpleSchema type
*/
2018-05-08 12:29:51 +09:00
export const getIntlString = () => {
const schema = {
locale: {
type: String,
optional: true,
},
value: {
2018-05-08 12:29:51 +09:00
type: String,
optional: true,
}
};
2018-05-08 12:29:51 +09:00
const IntlString = new SimpleSchema(schema);
IntlString.name = 'IntlString';
return IntlString;
}
/*
Custom validation function to check for required locales
See https://github.com/aldeed/simple-schema-js#custom-field-validation
*/
export const validateIntlField = function () {
let errors = [];
// if field is required, go through locales to check which one are required
if (!this.definition.optional) {
const requiredLocales = Locales.filter(locale => locale.required);
requiredLocales.forEach((locale, index) => {
const strings = this.value;
const hasString = strings.some(s => s.locale === locale.id && s.value);
const originalFieldName = this.key.replace('_intl', '');
if (!hasString) {
errors.push({ id: 'errors.required', path: `${this.key}.${index}`, properties: { name: `${originalFieldName}_${locale.id}`, label: `${originalFieldName} (${locale.id})` }});
}
});
}
// hack to work around the fact that custom validation function can only return a single string
return `intlError|${JSON.stringify(errors)}`;
2018-05-21 10:02:43 +09:00
}