-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTitanSchoolsClient.js
357 lines (321 loc) · 11.9 KB
/
TitanSchoolsClient.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
const axios = require("axios").default;
/**
* A _very_ lightweight client for the TitanSchools API.
*/
class TitanSchoolsClient {
constructor(config = {}) {
if (typeof config.buildingId === "undefined") {
throw new Error(
"TitanSchools API client needs a buildingId config value"
);
}
if (typeof config.districtId === "undefined") {
throw new Error(
"TitanSchools API client needs a districtId config value"
);
}
this.debug = config.debug === true;
this.requestParams = {
buildingId: config.buildingId,
districtId: config.districtId,
};
this.numberOfDaysToDisplay = config.numberOfDaysToDisplay;
this.recipeCategoriesToInclude = config.recipeCategoriesToInclude ?? [
"Main Entree", // Maybe deprecated?
"Entrees",
"Grain",
// , "Fruit"
// , "Vegetable"
// , "Milk"
// , "Condiment"
// , "Extra"
];
this.client = axios.create({
baseURL: "https://api.linqconnect.com/api/",
timeout: 30000,
});
}
async fetchMockMenu() {
const data = require("./test/unit/mocks/mockApiResponse");
return this.processData(data);
}
/**
* Fetches menu data from the TitanSchools API and formats it as shown below
*
* @param Date startDate A Date object that specifies which day the menu should start on
* @param Date endDate A Date object that specifies which day the menu should end on
* @throws Error If the TitanSchools API responds with a 400- or 500-level HTTP status
*
* @returns An array of meals shaped like this (starting on {startDate} and including {config.numberOfDaysToDisplay} days):
* [
* { "date": "9-6-2021", "label": "Today" },
* {
* "date": "9-7-2021",
* "label": "Tomorrow",
* "breakfast": "SCRAMBLED EGGS & FRENCH TOAST, APPLE,MIXED FRUIT,JUICE, APPLE 4 OZ.,JUICE, GRAPE 4 OZ.,JUICE, ORANGE 4 OZ., MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP",
* "lunch": "STUFFED CHEESE BREADSTICK, COOKIE VARIETY, MARINARA CUP,CARROTS- INDV PACKS, PEACHES SLICED, MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP, RANCH CUP"
* },
* {
* "date": "9-8-2021",
* "label": "Wednesday",
* "breakfast": "CEREAL LUCKY CHARMS GF, CEREAL, CINNAMON TOAST, JUICE, APPLE 4 OZ.,JUICE, GRAPE 4 OZ.,JUICE, ORANGE 4 OZ.,MIXED FRUIT,APPLE, MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP",
* "lunch": "CHICKEN SANDWICH, BEANS VEGETARIAN, PEARS SLICED, MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP, KETCHUP PACKET,RANCH CUP, LETTUCE & PICKLE CUP"
* },
* {
* "date": "9-9-2021",
* "label": "Thursday",
* "breakfast": "CHERRY FRUDEL, JUICE, APPLE 4 OZ.,JUICE, GRAPE 4 OZ.,JUICE, ORANGE 4 OZ.,MIXED FRUIT,APPLE, MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP",
* "lunch": "ORANGE CHICKEN, BROWN RICE, GREEN BEANS, APPLE, MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP"
* },
* {
* "date": "9-10-2021",
* "label": "Friday",
* "breakfast": "POP TART, CINNAMON,POP TART, STRAWBERRY, JUICE, APPLE 4 OZ.,JUICE, GRAPE 4 OZ.,JUICE, ORANGE 4 OZ.,PEACHES SLICED, MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP",
* "lunch": "HAMBURGER, GARDEN SALAD, PEACH CUP ZEE ZEE, MILK CHOCOLATE FF CARTON HP,MILK WHITE 1% CARTON HP, KETCHUP PACKET,MUSTARD PACKET,RANCH CUP, LETTUCE & PICKLE CUP"
* }
* ]
*/
async fetchMenu(startDate, endDate) {
let params = {
...this.requestParams,
// API requires dates to be formatted as: m-d-Y (i.e. 12-5-2021)
startDate: this.formatDate(startDate),
endDate: this.formatDate(endDate)
};
if (this.debug) {
console.debug(`Using ${params.startDate} as startDate, ${params.endDate} as endDate`);
// Log the outbound API request
this.client.interceptors.request.use((request) => {
console.debug(
`Sending API request: ${JSON.stringify({
url: request.url,
params: request.params,
})}`
);
return request;
});
}
try {
const axiosResponse = await this.client.get("/FamilyMenu", {
params,
});
return this.processData(axiosResponse.data);
} catch (error) {
if (error.response?.status && error.response.status >= 500) {
throw new Error(
`The TitanSchools API is unavailable: ${error.response.data?.error_description}`
);
} else if (error.response?.status && error.response.status >= 400) {
throw new Error(
`The TitanSchools API sure didn't like the request we sent and responded with: ${
error.response.data?.error_description || error.response.status
}. Maybe double check your config values.`
);
} else {
throw error;
}
}
}
/**
*
* @param Date dateObject A Date object
* @returns string A date string formatted as m-d-Y (1-9-2023)
*/
formatDate(dateObject) {
return `${
dateObject.getMonth() + 1 // javascript month is 0-indexed :facepalm:
}-${dateObject.getDate()}-${dateObject.getFullYear()}`;
}
/**
* Takes in a raw response body from the TitanSchools API and outputs a normalized array of menus by date.
* Since the TitanSchools API has the potential to change without warning, this function will isolate breaking
* API changes and output normalized data that the rest of the functions can assume to be correct.
*
* @param Object apiResponse The response body from the TitanSchools API.
*/
extractMenusByDate(apiResponse) {
if (!Object.hasOwnProperty.call(apiResponse, "FamilyMenuSessions")) {
if (this.debug) {
console.log(
`TitanSchools API response did not contain the expected data: ${apiResponse}`
);
} else {
console.log(
`TitanSchools API response did not contain the expected data. Set 'debug: true' in the modules.MMM-TitanSchoolMealMenu section of config.json file for verbose logs`
);
}
return [];
}
const menus = apiResponse.FamilyMenuSessions.map((menuSession) => {
// The titank12 API has several possible values for the ServingSession,
// including "Breakfast", "Lunch", "Seamless Summer Lunch", "Seamless Summer Breakfast".
const breakfastOrLunch = menuSession.ServingSession.match(/breakfast/i)
? "breakfast"
: "lunch";
const menusByDate = menuSession.MenuPlans[0].Days.map(
(menuForThisDate) => {
// Just for logging/troubleshooting, keep track of all the recipes in this menu and note which ones get
// intentionally filtered out.
const recipesToLog = {
all: [],
filteredOut: [],
};
if (!menuForThisDate.MenuMeals[0]?.RecipeCategories[0]?.Recipes[0]) {
if (this.debug) {
console.debug(
`No meal data was found in the API response for ${menuForThisDate.Date}. Expected to find MenuMeals[].RecipeCategories[].Recipes, but got: ${menuForThisDate}`
);
}
return [];
}
const recipeCategories = menuForThisDate.MenuMeals.map((mealLine) => {
return mealLine.RecipeCategories.filter((recipeCategory) => {
if (!recipesToLog.all.includes(recipeCategory.CategoryName)) {
recipesToLog.all.push(recipeCategory.CategoryName);
}
if (this.recipeCategoriesToInclude.length === 0
|| this.recipeCategoriesToInclude.includes(
recipeCategory.CategoryName
)
) {
return true;
} else {
if (
!recipesToLog.filteredOut.includes(
recipeCategory.CategoryName
)
) {
recipesToLog.filteredOut.push(recipeCategory.CategoryName);
}
return false;
}
});
}, this).flat();
if (this.debug) {
let message = `The ${breakfastOrLunch} menu for ${
menuForThisDate.Date
} contains the following categories: ${recipesToLog.all.join(
", "
)}`;
if (recipesToLog.filteredOut.length > 0) {
message += `, but ${recipesToLog.filteredOut.join(
", "
)} were filtered out because they're not included in the config.recipeCategoriesToInclude array.`;
}
console.debug(message);
}
return {
date: menuForThisDate.Date,
breakfastOrLunch,
menu: recipeCategories
.map((recipeCategory) => {
return recipeCategory.Recipes.map(
(recipe) => recipe.RecipeName
).join(" or ");
})
.join(", "),
};
},
this
);
return menusByDate;
}, this);
if (this.debug) {
console.debug(
`Menus extracted from the TitanSchools API response: ${JSON.stringify(
menus
)}`
);
}
return menus;
}
processData(data) {
const menus = this.extractMenusByDate(data);
const upcomingMenuByDate = upcomingRelativeDates(this.numberOfDaysToDisplay).map((day) => {
// day = { date: '9-6-2021', label: 'Today' }; // Possible labels: 'Today', 'Tomorrow', or a day of the week
const breakfastAndLunchForThisDay = menus.reduce(
(menuByMealTime, menu) => {
const menuForThisDate = menu.filter((menuForOneDate) => {
const date1 = new Date(menuForOneDate.date);
const date2 = new Date(day.date);
return !(date1 > date2) && !(date1 < date2); // Checking for date equality
});
if (!menuForThisDate[0]) {
return menuByMealTime;
}
return {
...menuByMealTime,
[menuForThisDate[0].breakfastOrLunch.toLowerCase()]:
menuForThisDate[0].menu,
};
},
{}
);
return {
date: day.date,
label: day.label,
breakfast: breakfastAndLunchForThisDay.breakfast,
lunch: breakfastAndLunchForThisDay.lunch,
};
});
console.log(
`School meal info from titanschools API: ${JSON.stringify(
upcomingMenuByDate
)}`
);
return upcomingMenuByDate;
}
}
/**
* Returns an array of the next 7 dates shaped like this:
* [
* { date: '9-6-2021', label: 'Today' },
* { date: '9-7-2021', label: 'Tomorrow' },
* { date: '9-8-2021', label: 'Wednesday' },
* { date: '9-9-2021', label: 'Thursday' },
* { date: '9-10-2021', label: 'Friday' },
* { date: '9-11-2021', label: 'Saturday' },
* { date: '9-12-2021', label: 'Sunday' }
* ]
*/
const upcomingRelativeDates = (numberOfDays = 5) => {
const dayOfWeek = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
let weekOfRelativeDates = [];
for (let dayOffset = 0; dayOffset < numberOfDays; dayOffset++) {
const now = new Date(Date.now());
let adjustedDate = new Date(Date.now());
adjustedDate.setDate(now.getDate() + parseInt(dayOffset, 10));
const date = `${
adjustedDate.getMonth() + 1 // javascript month is 0-indexed :facepalm:
}-${adjustedDate.getDate()}-${adjustedDate.getFullYear()}`;
let label = "";
if (dayOffset === -1) {
label = "Yesterday";
} else if (dayOffset === 0) {
label = "Today";
} else if (dayOffset === 1) {
label = "Tomorrow";
} else {
label = dayOfWeek[adjustedDate.getDay()];
}
weekOfRelativeDates.push({
date,
label,
});
}
return weekOfRelativeDates;
};
// const t = new TitanSchoolsClient({
// buildingId: '23125610-cbbc-eb11-a2cb-82fe13669c55',
// districtId: '93f76ff0-2eb7-eb11-a2c4-e816644282bd',
// });
// t.fetchMockMenu();
module.exports = TitanSchoolsClient;