-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdogs.ts
117 lines (100 loc) · 2.79 KB
/
dogs.ts
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
117
require("encoding");
import type { APIGatewayEvent, Context } from "aws-lambda";
import dotenv from "dotenv-flow";
import type { PetFinderToken } from "./util/PetFinder/types";
import {
refetchAuthTokenIfExpired,
getDogsFromPetFinder,
} from "./util/PetFinder/api";
import { getDogsFromAdoptAPet } from "./util/AdoptAPet/api";
dotenv.config();
const { PETFINDER_API_KEY, PETFINDER_API_KEY_SECRET, PORT } = process.env;
/** The current API token to hit Petfinder */
let currentToken: PetFinderToken | undefined = undefined;
/** Query params passed in to /dogs */
interface DogsQueryParams {
/** Location to find dogs in */
location?: string;
/** Whether or not to apply the apartment friendly filter */
apartmentFriendly?: string;
/** Current page to fetch */
page?: string;
}
export async function handler(event: APIGatewayEvent, context: Context) {
if (!PETFINDER_API_KEY || !PETFINDER_API_KEY_SECRET) {
return {
statusCode: 500,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
message: "API key or API key secret not configured!",
}),
};
}
if (!event.queryStringParameters) {
return {
statusCode: 400,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
message: "Query string parameters not present",
}),
};
}
const {
location,
apartmentFriendly,
page,
}: DogsQueryParams = event.queryStringParameters;
const applyApartmentFriendlyFilter = apartmentFriendly === "true";
const currentPage = page ? Number.parseInt(page, 10) : 0;
const locationToUse = location || "98122";
try {
currentToken = await refetchAuthTokenIfExpired(
PETFINDER_API_KEY,
PETFINDER_API_KEY_SECRET,
currentToken
);
const dogs = (
await Promise.all([
await getDogsFromPetFinder(
currentToken.access_token,
locationToUse,
currentPage,
applyApartmentFriendlyFilter
),
await getDogsFromAdoptAPet(
locationToUse,
currentPage,
applyApartmentFriendlyFilter
),
])
).flat();
return {
statusCode: 200,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
animals: dogs,
pagination: {
nextPage: currentPage + 1,
},
}),
};
} catch (error) {
// if we get this back, it means that the token is probably expired and we should try and fetch a new one...
if (error.data?.detail?.includes("Access token invalid or expired")) {
currentToken = undefined;
}
return {
statusCode: 500,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(error),
};
}
}