-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (69 loc) · 1.72 KB
/
index.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
83
84
85
86
87
88
89
import { Router, cors, error } from 'itty-router';
import { csfd } from 'node-csfd-api';
const { preflight, corsify } = cors();
const router = Router({
before: [preflight],
finally: [corsify],
});
router.get('/detail/:movieortv', async ({ params, query }) => {
const movieOrTv = params.movieortv;
const name = query.name;
const year = query.year;
if (name === undefined) {
return error(400, 'Invalid movie name');
}
try {
const searchResponse = await csfd.search(name);
let searchResults;
if (movieOrTv === 'movie') {
searchResults = searchResponse.movies;
} else if (movieOrTv === 'tv') {
searchResults = searchResponse.tvSeries;
} else {
return error(400, 'Invalid movie/tv type');
}
if (year !== undefined) {
const parsedYear = parseInt(year);
if (isNaN(parsedYear)) {
return error(400, 'Invalid year');
}
searchResults = searchResults.filter((movie) => movie.year === parsedYear);
}
if (searchResults.length === 0) {
return error(404, 'No movies / tv found');
}
const id = searchResults[0].id;
const movieResponse = await csfd.movie(id);
return new Response(JSON.stringify(movieResponse), {
headers: {
'Content-Type': 'application/json',
},
});
} catch (e) {
console.error(e);
return error(500);
}
});
router.get('/tmdb', ({ headers }, env) => {
const password = headers.get('password');
if (password !== env.TMDB_PASSWORD) {
return error(401);
}
return new Response(
JSON.stringify({
accessToken: env.TMDB_ACCESS_TOKEN,
}),
{
headers: {
'Content-Type': 'application/json',
},
}
);
});
router.all('*', () => {
return error(404);
});
export default {
// https://itty.dev/itty-router/guides/cloudflare-workers
...router,
};