/ src / api / menus.ts
menus.ts
 1  import type * as definitions from "~/definitions";
 2  import type { Meal } from "~/models";
 3  import { deserialize } from "desero";
 4  import { HttpRequest, send } from "schwi";
 5  import { BASE_URL } from "~/core/constants";
 6  import { Menu } from "~/models";
 7  
 8  /**
 9   * Get all {@link Menu|menus} for a given identifier and restaurant.
10   *
11   * @param identifier - Where we should look for restaurants.
12   * @param restaurant - Where we should look for menus.
13   * @returns A list of all {@link Menu|menu} for the given restaurant.
14   *
15   * @example
16   * const menus = await getMenusFrom("limoges", "r211");
17   */
18  export async function getMenusFrom(identifier: string, restaurant: string): Promise<Array<Menu>> {
19    const request = new HttpRequest.Builder(BASE_URL + `${identifier}/externe/menu2014.xml`).build();
20    const response = await send(request);
21  
22    const xml = await response.toXML<{
23      listemenus: {
24        menu: Array<definitions.menu>;
25      };
26    }>();
27  
28    return xml.listemenus.menu.filter(
29      (menu) => menu.restaurant === restaurant
30    ).map((menu) => deserialize(Menu, menu));
31  };
32  
33  export async function getMealsFromForDate(identifier: string, restaurant: string, date = new Date()): Promise<Array<Meal> | null> {
34    const menus = await getMenusFrom(identifier, restaurant);
35  
36    return menus.find((menu) =>
37      menu.date.getDate() === date.getDate()
38      && menu.date.getMonth() === date.getMonth()
39    )?.meals ?? null;
40  }