Skip to content

Commit

Permalink
Simplify tmdb-refresher into a single worker
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed Apr 8, 2024
1 parent 089a5d2 commit 7bfdc88
Show file tree
Hide file tree
Showing 18 changed files with 219 additions and 293 deletions.
1 change: 0 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ jobs:
- metrics
- stripe-hooks
- tmdb-refresher
- tmdb-refresher-scheduler

steps:
- uses: actions/checkout@v3
Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ Important links:
- [metrics worker](https://dash.cloudflare.com/9bfdb755def60e50760e33036c6f1624/workers/services/view/watch-metrics/production)
- [stripe worker](https://dash.cloudflare.com/9bfdb755def60e50760e33036c6f1624/workers/services/view/watch-stripe/production)
- [tmdb-refresher worker](https://dash.cloudflare.com/9bfdb755def60e50760e33036c6f1624/workers/services/view/watch-tmdb-refresher/production)
- [tmdb-refresher-scheduler worker](https://dash.cloudflare.com/9bfdb755def60e50760e33036c6f1624/workers/services/view/watch-tmdb-refresher-scheduler/production)
- [Fly.io dashboard](https://fly.io/apps/watch-test-app)
- [PlanetScale dashboard](https://app.planetscale.com/chris-sauve/watch-test-db)
- [Google Cloud dashboard](https://console.cloud.google.com/welcome?project=watch-353105&_ga=2.12737845.383552117.1655603476-570853528.1655012838) ([Dev OAuth app](https://console.cloud.google.com/apis/credentials/oauthclient/357202806916-9ed7sce9ddqkb5hia8tvkl0pshleih2h.apps.googleusercontent.com?project=watch-353105))
Expand Down
3 changes: 0 additions & 3 deletions functions/tmdb-refresher-scheduler/README.md

This file was deleted.

12 changes: 0 additions & 12 deletions functions/tmdb-refresher-scheduler/configuration/rollup.config.js

This file was deleted.

13 changes: 0 additions & 13 deletions functions/tmdb-refresher-scheduler/package.json

This file was deleted.

47 changes: 0 additions & 47 deletions functions/tmdb-refresher-scheduler/tmdb-refresher-scheduler.ts

This file was deleted.

13 changes: 0 additions & 13 deletions functions/tmdb-refresher-scheduler/tsconfig.json

This file was deleted.

19 changes: 0 additions & 19 deletions functions/tmdb-refresher/configuration/wrangler.toml

This file was deleted.

105 changes: 105 additions & 0 deletions functions/tmdb-refresher/handlers/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import {updateSeries} from '~/global/tmdb.ts';
import {createPrisma, type Environment} from './shared.ts';

export async function handleFetch(request: Request, env: Environment) {
if (request.method !== 'POST') {
// response with method not allowed status
return new Response(
JSON.stringify({
error: {message: 'You can only use HTTP POST for this request.'},
}),
{
status: 405,
headers: {
Allow: 'POST',
'Content-Type': 'application/json',
},
},
);
}

const token = request.headers.get('TMDB-Access-Token');

if (token !== env.TMDB_ACCESS_TOKEN) {
return new Response(
JSON.stringify({
error: {
message:
'You must provide the TMDB token in the TMDB-Access-Token header of the request.',
},
}),
{
status: 401,
headers: {
'Content-Type': 'application/json',
},
},
);
}

try {
const options = (await request.json()) as {
id?: string | number;
handle?: string;
};
const idOption = options.id ? String(options.id) : undefined;
const handleOption = options.handle;

if (typeof idOption !== 'string' && typeof handleOption !== 'string') {
return new Response(
JSON.stringify({
error: {
message:
'You must provide either an `id` or `handle` option in your JSON request body.',
},
}),
{
status: 400,
headers: {
'Content-Type': 'application/json',
},
},
);
}

const prisma = await createPrisma(env.DATABASE_URL);
const {id, name, tmdbId} = await prisma.series.findUniqueOrThrow({
where: idOption ? {id: idOption} : {handle: handleOption},
select: {id: true, name: true, tmdbId: true},
});

const {results} = await updateSeries({
id,
name,
tmdbId,
prisma,
accessToken: env.TMDB_ACCESS_TOKEN,
});

const result = results.join('\n\n');
console.log(result);

return new Response(JSON.stringify({}), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
console.error(error);

return new Response(
JSON.stringify({
error: {
message: 'There was an error while updating series.',
},
}),
{
status: 500,
headers: {
'Content-Type': 'application/json',
},
},
);
}
}
43 changes: 43 additions & 0 deletions functions/tmdb-refresher/handlers/queue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {updateSeries} from '~/global/tmdb.ts';
import {createPrisma, type Environment, type Message} from './shared.ts';
import type {MessageBatch} from '@cloudflare/workers-types';

export async function handleQueue(
batch: MessageBatch<Message>,
env: Environment,
) {
const prisma = await createPrisma(env.DATABASE_URL);

try {
await Promise.all(
batch.messages.map(async ({body: {id, name, tmdbId}}) => {
const {results} = await updateSeries({
id,
name,
tmdbId,
prisma,
accessToken: env.TMDB_ACCESS_TOKEN,
});

const result = results.join('\n\n');
console.log(result);

const fetchResult = await fetch(
'https://discordapp.com/api/webhooks/656640833063223325/1ofugrkDFpqaSAWvD6mLlg5EN3UDOfBdib4WKNE17Q5YxUoz8wpwuLoKCeaZJqCHyfeC',
{
method: 'POST',
body: JSON.stringify({
content: result,
}),
headers: {'Content-Type': 'application/json'},
},
);

console.log(fetchResult);
}),
);
} catch (error) {
console.log((error as any)?.stack);
throw error;
}
}
29 changes: 29 additions & 0 deletions functions/tmdb-refresher/handlers/schedule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type {ScheduledEvent} from '@cloudflare/workers-types';
import {createPrisma, type Environment} from './shared';

export async function handleScheduled(event: ScheduledEvent, env: Environment) {
console.log(JSON.stringify(event, null, 2));

try {
const prisma = await createPrisma(env.DATABASE_URL);

const series = await prisma.series.findMany({
where: {status: 'RETURNING'},
});

console.log(series);

await Promise.all(
series.map(async (series) => {
await env.TMDB_REFRESHER_QUEUE.send({
id: series.id,
name: series.name,
tmdbId: series.tmdbId,
});
}),
);
} catch (error) {
console.error(error);
throw error;
}
}
21 changes: 21 additions & 0 deletions functions/tmdb-refresher/handlers/shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type {Queue} from '@cloudflare/workers-types';
import {createEdgeDatabaseConnection} from '~/global/database.ts';

export interface Environment {
DATABASE_URL: string;
TMDB_ACCESS_TOKEN: string;
TMDB_REFRESHER_QUEUE: Queue<Message>;
}

export interface Message {
id: string;
name: string;
tmdbId: string;
}

let prismaPromise: Promise<import('@prisma/client').PrismaClient> | undefined;

export async function createPrisma(url: string) {
prismaPromise ??= createEdgeDatabaseConnection({url});
return await prismaPromise;
}
4 changes: 2 additions & 2 deletions functions/tmdb-refresher/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"private": true,
"types": "./tmdb-refresher.ts",
"scripts": {
"build": "rollup --config ./configuration/rollup.config.js",
"deploy": "wrangler deploy --config ./configuration/wrangler.toml"
"build": "rollup --config ./rollup.config.js",
"deploy": "wrangler deploy --config ./wrangler.toml"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20221111.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {quiltModule} from '@quilted/rollup/module';
import {cloudflareWorkers} from '@quilted/cloudflare/craft';
import {prismaFromEdge} from '../../../configuration/rollup/prisma.js';
import {prismaFromEdge} from '../../configuration/rollup/prisma.js';

const config = await quiltModule({
entry: './tmdb-refresher.ts',
Expand Down
Loading

0 comments on commit 7bfdc88

Please sign in to comment.