strapi-to-lokalise-plugin
Version:
Preview and sync Lokalise translations from Strapi admin
72 lines (59 loc) • 1.6 kB
JavaScript
;
const STORE_KEY = 'keyRenames';
const getStore = () =>
strapi.store({
type: 'plugin',
name: 'lokalise-sync',
});
const normalizeUpdates = (updates = {}) => {
const normalized = {};
Object.entries(updates).forEach(([key, value]) => {
if (typeof value === 'string') {
normalized[key] = value.trim();
} else {
normalized[key] = value;
}
});
return normalized;
};
const splitId = (id = '') => {
const [type, ...rest] = id.split('::');
const original = rest.join('::');
return { type, original };
};
module.exports = {
async getAll() {
const store = getStore();
const value = await store.get({ key: STORE_KEY });
return value || {};
},
async setAll(value) {
const store = getStore();
await store.set({ key: STORE_KEY, value });
return value;
},
async update(updates = {}) {
const current = await this.getAll();
const next = { ...current };
const normalized = normalizeUpdates(updates);
Object.entries(normalized).forEach(([id, newValue]) => {
const { type, original } = splitId(id);
if (!type || !original) {
return;
}
if (!next[type]) {
next[type] = {};
}
if (!newValue || newValue === original) {
delete next[type][original];
if (Object.keys(next[type]).length === 0) {
delete next[type];
}
} else {
next[type][original] = newValue;
}
});
await this.setAll(next);
return next;
},
};