UNPKG

simple-body-validator

Version:

This package is inspired by Laravel validation, and aims to make body validation easier for Javascript developers

96 lines (95 loc) 2.9 kB
'use strict'; import { mergeDeep } from './utils/object'; import locales from './locales/index'; const lang = { /** * Default lang to be used, when lang is not specified */ defaultLang: 'en', /** * Determines the locale to be used when tu current one is not available */ fallbackLang: 'en', /** * The existing langs that are supported by the library */ existingLangs: ['en'], /** * Store the translations passed by the user */ translations: {}, /** * Stores the messages that are already loaded */ messages: {}, /** * Stores the default messages */ defaultMessages: {}, /** * Stores the fallback messages */ fallbackMessages: locales.en, /** * Get messages for lang */ get(lang = this.defaultLang) { this.load(lang); return this.messages[lang]; }, /** * Set the translation object passed by the user */ setTranslationObject(translations) { this.translations = translations; this.setDefaultLang(this.defaultLang); }, /** * Set the default lang that should be used. And assign the default messages */ setDefaultLang(lang) { this.defaultLang = lang; this.load(lang); }, /** * Set the fallback lang to be used. And assign the fallback messages */ setFallbackLang(lang) { this.fallbackLang = lang; this.fallbackMessages = locales.en; // check if the lang translations exist in the library and load them if (locales.hasOwnProperty(lang)) { this.fallbackMessages = mergeDeep(this.fallbackMessages, locales[lang]); } // check if the lang translations exit in the object passed by the user if (this.translations.hasOwnProperty(lang)) { this.fallbackMessages = mergeDeep(this.fallbackMessages, this.translations[lang]); } }, /** * Get the default language */ getDefaultLang() { return this.defaultLang; }, /** * Load the messages based on the specified language */ load(lang) { if (this.messages[lang]) { return; } // check if the lang translations exist in the library and load them if (locales.hasOwnProperty(lang)) { this.messages[lang] = mergeDeep(this.fallbackMessages, locales[lang]); } else { this.messages[lang] = mergeDeep({}, this.fallbackMessages); } // check if the lang translations exist in the object passed by the user if (this.translations.hasOwnProperty(lang)) { this.messages[lang] = mergeDeep(this.messages[lang], this.translations[lang]); } } }; export default lang;