-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathAlgolia.js
82 lines (71 loc) · 2.3 KB
/
Algolia.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const algoliasearch = require("algoliasearch");
const core = require("@actions/core");
require("dotenv").config(); // Load environment variables from .env file
// Initialize Algolia client and index using environment variables
const client = algoliasearch(
process.env.ALGOLIA_APP_ID,
process.env.ALGOLIA_API_KEY
);
const index = client.initIndex(process.env.ALGOLIA_INDEX_NAME);
// Function to process each file
async function processFile(entry) {
if (fs.existsSync(entry)) {
// If the file exists, read and parse the JSON content
const fileContent = JSON.parse(fs.readFileSync(entry, "utf8"));
const [name, data] = Object.entries(fileContent)[0];
core.info(`Updating ${name}`);
// Add name and objectID to the data
data.name = name;
data.objectID = data.domain;
// Rename keys if necessary
const { tfa, categories, ...rest } = data;
const renamedData = {
...rest,
...(tfa && { "2fa": tfa }),
...(categories && { category: categories }),
};
return renamedData;
} else {
// If the file does not exist, remove the corresponding object from Algolia
const domain = path.basename(entry, ".json");
core.info(`Removing ${domain}`);
await index.deleteObject(domain);
return null;
}
}
// Main function to process files and update the Algolia index
async function main() {
const files = process.argv.slice(2); // Get the list of files from command-line arguments
const updates = [];
let errors = false;
// Process each file in parallel
const results = await Promise.allSettled(
files.map(async (entry) => processFile(entry))
);
results.forEach((result) => {
if (result.status === "fulfilled" && result.value) {
updates.push(result.value);
} else if (result.status === "rejected") {
errors = true;
core.error(`Failed to process a file: ${result.reason}`);
}
});
// If there are updates, save them to the Algolia index
if (updates.length > 0) {
try {
await index.saveObjects(updates);
core.info("All updates saved");
} catch (err) {
core.error("Error saving updates:", err);
errors = true;
}
}
process.exit(+errors);
}
main().catch((err) => {
core.error(err);
process.exit(1);
});