-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistributeRanks.ts
More file actions
116 lines (87 loc) · 2.81 KB
/
DistributeRanks.ts
File metadata and controls
116 lines (87 loc) · 2.81 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import dotenv from "dotenv";
dotenv.config();
import { Client, LogLevel } from "@notionhq/client";
import { DatabasesQueryParameters, PagesUpdateParameters } from "@notionhq/client/build/src/api-endpoints";
const databaseID = "09af3c9f29d346c3a3a072a6d4b80ada";
const rankPropertyName = "Rank";
class Movie {
name: string;
pageID: string;
rank: number;
newRank: number;
constructor(pageID: string, name: string, rank: number) {
this.pageID = pageID;
this.name = name;
this.rank = rank;
this.newRank = rank;
}
public static fromPage(page : any) {
return new Movie(
page.id,
page.properties.Name.title[0].plain_text,
page.properties.Rank.number
);
}
public toString(){
var result = this.name;
return result;
}
}
const main = async () => {
const client = new Client({
"auth": process.env.NOTION_TOKEN,
"logLevel": LogLevel.DEBUG,
});
const movies = await getMovies(client);
const orderedUniqueRanks = getOrderedUniqueRanks(movies);
movies.forEach(t => t.newRank = orderedUniqueRanks.indexOf(t.rank) + 1);
for (const movie of movies) {
await updateRank(client, movie);
}
};
const getOrderedUniqueRanks = (movies : Movie[]) => {
const result = [...new Set(movies.map(t => t.rank))];
result.sort((a,b) => a - b);
return result;
};
const getMovies = async (client : Client) : Promise<Movie[]> => {
let hasMore = true;
let nextCursor : string | null = null;
const moviePages = [];
while (hasMore){
const request : DatabasesQueryParameters = {
"database_id": databaseID,
"sorts": [
{
"property": rankPropertyName,
"direction": "ascending",
}
],
};
if (nextCursor !== null)
request.start_cursor = nextCursor;
const response = await client.databases.query(request);
moviePages.push(...response.results);
hasMore = response.has_more;
nextCursor = response.next_cursor;
}
const pages = moviePages.filter(p => p.properties.Rank).map(Movie.fromPage);
return pages;
};
const updateRank = async (client : Client, movie : Movie) => {
if (movie.rank === movie.newRank){
console.log(`Movie '${movie.toString()}' already has a rank of ${movie.rank}.`);
return;
}
console.log(`Update movie '${movie.toString()}' from ${movie.rank} to ${movie.newRank}.`);
const request = {
"page_id": movie.pageID,
"properties": {
[rankPropertyName]: {
"number": movie.newRank
}
},
};
await client.pages.update(request as unknown as PagesUpdateParameters);
};
main();