1
Get new files Trigger
One script reply has been approved by the moderators Verified

Trigger script to periodically get the newly uploaded files.

Created by adam186 795 days ago Viewed 15458 times
In Windmill, a trigger script is designed to pull data from an external source and return all the new items since the last run. It operates without resorting to external webhooks and is typically used with schedules and states to compare the current execution to the previous one.
0
Submitted by adam186 Deno
Verified 795 days ago
1
import {
2
  getState,
3
  setState,
4
} from "https://deno.land/x/windmill@v1.85.0/mod.ts";
5
import { drive } from "npm:@googleapis/drive@4";
6

7
const PAGE_SIZE = 500 as const;
8

9
/**
10
 * @returns A list of newly uploaded files in ascending order
11
 * of creation date.
12
 * Maximum number of returned items is set to `500` for each run.
13
 */
14
type Gdrive = {
15
  token: string;
16
};
17
export async function main(auth: Gdrive) {
18
  const client = drive({
19
    version: "v3",
20
    headers: {
21
      Authorization: `Bearer ${auth.token}`,
22
    },
23
  });
24

25
  const lastCheck = await getState();
26
  await setState(new Date().toISOString());
27
  const response = await client.files.list({
28
    q: lastCheck ? `createdTime > '${lastCheck}'` : undefined,
29
    orderBy: "createdTime asc",
30
    pageSize: PAGE_SIZE,
31
  });
32
  if (response.data.nextPageToken && response?.data?.files?.at(-1)) {
33
    const lastItem = await client.files.get({
34
      fileId: response.data.files.at(-1)?.id || undefined,
35
      fields: "createdTime",
36
    });
37
    const date = lastItem?.data?.createdTime;
38
    if (date) {
39
      await setState(date);
40
    }
41
  }
42

43
  return response.data.files;
44
}
45