Skip to content

Commit 481ddc9

Browse files
committed
collection-restore-patch
1 parent 6b632a9 commit 481ddc9

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

scripts/restore-collection.mjs

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,19 @@ import path from "path";
99

1010
const require = Module.createRequire(import.meta.url);
1111

12+
const HAS_COLLECTION_ATTRIBUTE = (collectionId, attributeKey) => {
13+
const collection = schema.collections.find(
14+
(item) => item.$id === collectionId
15+
);
16+
if (!collection) {
17+
return false;
18+
}
19+
const attribute = collection.attributes.find(
20+
(item) => item.key === attributeKey
21+
);
22+
return !!attribute;
23+
};
24+
1225
if (!existsSync(".env")) {
1326
console.log("Missing .env file. Please use .env.example as a template");
1427
process.exit(-1);
@@ -45,6 +58,27 @@ if (process.env.APPWRITE_SELF_SIGNED) {
4558

4659
const databases = new sdk.Databases(client);
4760

61+
const tryRead = async (databaseId, collectionId, documentId) => {
62+
try {
63+
return await databases.getDocument(databaseId, collectionId, documentId);
64+
} catch {
65+
return null;
66+
}
67+
};
68+
69+
const writeTransform = (data, collectionId) => {
70+
const userEntries = Object.entries(data)
71+
.filter(([key]) => !key.startsWith("$"))
72+
.filter(([key]) => {
73+
const hasAttribute = HAS_COLLECTION_ATTRIBUTE(collectionId, key);
74+
if (!hasAttribute) {
75+
console.log(`SKIP ATTRIBUTE key=${key} collection=${collectionId}`);
76+
}
77+
return hasAttribute;
78+
})
79+
return Object.fromEntries(userEntries);
80+
};
81+
4882
const sleep = (timeout = 1_000) =>
4983
new Promise((res) => {
5084
setTimeout(() => {
@@ -59,18 +93,18 @@ await fs.mkdir("backup/databases", { recursive: true });
5993
console.log(`Found ${total} databases!`);
6094
for (const database of databasesList) {
6195
const collections = entries.map(FIND_COLLECTION);
62-
console.log(`Found ${total} collections id ${database.$id}!`);
96+
console.log(`Found ${collections.length} collections id ${database.$id}!`);
6397
for (const collection of collections) {
6498
const databaseFiles = await glob(
65-
`backup/databases/*/${collection}/*.json`,
99+
`backup/databases/*/${collection.$id}/*.json`,
66100
{
67101
withFileTypes: true,
68102
stat: true,
69103
},
70104
);
71105
databaseFiles.sort((a, b) => a.mtime - b.mtime);
72106
console.log(
73-
`Found ${databaseFiles.length} collection ${collection} documents`,
107+
`Found ${databaseFiles.length} collection ${collection.$id} documents`,
74108
);
75109
for (const fileRef of databaseFiles) {
76110
const file = fileRef.fullpathPosix();

0 commit comments

Comments
 (0)