sheets-translate-to-json
Version:
A Node.js library that facilitates the retrieval and conversion of previously translated Google Sheets spreadsheets into structured JSON files, optimizing the management of localized resources.
171 lines (170 loc) • 5.24 kB
JavaScript
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/index.ts
import { GoogleSpreadsheet } from "google-spreadsheet";
import { JWT } from "google-auth-library";
import fs from "fs";
import path from "path";
var SheetManager = class {
constructor(privateKey, clientEmail, sheetId) {
const SCOPES = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file"
];
this.jwt = new JWT({
email: clientEmail,
key: privateKey,
scopes: SCOPES
});
this.doc = new GoogleSpreadsheet(sheetId, this.jwt);
}
init(userPath, sheetNames) {
return __async(this, null, function* () {
try {
yield this.jwt.authorize();
if (sheetNames && sheetNames.length > 0) {
for (const sheetName of sheetNames) {
const data = yield this.readByName(sheetName);
if (data && Object.keys(data).length > 0) {
this.write(data, userPath, sheetName);
} else {
console.warn(`No data found in sheet: ${sheetName}`);
}
}
} else {
const data = yield this.read();
if (data && Object.keys(data).length > 0) {
this.write(data, userPath);
} else {
console.error("No data found in the sheet");
}
}
} catch (err) {
console.error("Error during initialization:", err);
}
});
}
read(sheetPosition = 0) {
return __async(this, null, function* () {
if (sheetPosition < 0) {
sheetPosition = 0;
}
yield this.doc.loadInfo();
const sheet = this.doc.sheetsByIndex[sheetPosition];
return this.processSheet(sheet);
});
}
readByName(sheetName) {
return __async(this, null, function* () {
yield this.doc.loadInfo();
const sheet = this.doc.sheetsByTitle[sheetName];
if (!sheet) {
throw new Error(`Sheet with name "${sheetName}" not found`);
}
return this.processSheet(sheet);
});
}
readAllSheets() {
return __async(this, null, function* () {
yield this.doc.loadInfo();
const allData = {};
for (const sheet of this.doc.sheetsByIndex) {
try {
const data = yield this.processSheet(sheet);
if (data && Object.keys(data).length > 0) {
allData[sheet.title] = data;
}
} catch (error) {
console.error(`Error processing sheet "${sheet.title}":`, error);
}
}
return allData;
});
}
processSheet(sheet) {
return __async(this, null, function* () {
yield sheet.loadHeaderRow();
const colTitles = sheet.headerValues;
const rows = yield sheet.getRows({ limit: sheet.rowCount });
const result = {};
rows.forEach((row) => {
const keyValue = row.get(colTitles[0]);
if (!keyValue || keyValue.trim() === "") {
return;
}
colTitles.slice(1).forEach((title) => {
const key = keyValue.trim();
const value = row.get(title);
const cleanValue = value && value.trim() !== "" ? value.trim() : void 0;
if (!result[title]) {
result[title] = {};
}
if (key.includes(".")) {
this.setNestedValue(result[title], key, cleanValue);
} else {
result[title][key] = cleanValue;
}
});
});
return result;
});
}
setNestedValue(obj, keyPath, value) {
const keys = keyPath.split(".");
let current = obj;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (!current[key] || typeof current[key] !== "object") {
current[key] = {};
}
current = current[key];
}
const finalKey = keys[keys.length - 1];
current[finalKey] = value;
}
write(data, directoryPath, sheetPrefix) {
if (!fs.existsSync(directoryPath)) {
fs.mkdirSync(directoryPath, { recursive: true });
}
Object.keys(data).forEach((key) => {
const fileName = sheetPrefix ? `${sheetPrefix}_${key}.json` : `${key}.json`;
const filePath = path.join(directoryPath, fileName);
fs.writeFile(filePath, JSON.stringify(data[key], null, 2), (err) => {
if (err) {
console.error(`Error writing file ${filePath}:`, err);
return;
}
console.log(`File written: ${filePath}`);
});
});
}
// Méthode utilitaire pour lister toutes les feuilles disponibles
listSheets() {
return __async(this, null, function* () {
yield this.doc.loadInfo();
return this.doc.sheetsByIndex.map((sheet) => sheet.title);
});
}
};
export {
SheetManager
};
//# sourceMappingURL=index.mjs.map