/ src / api / restaurants.ts
restaurants.ts
 1  import type * as definitions from "~/definitions";
 2  import { deserialize } from "desero";
 3  import { HttpRequest, send } from "schwi";
 4  import { BASE_URL } from "~/core/constants";
 5  import { Restaurant } from "~/models";
 6  
 7  /**
 8   * Get all {@link Restaurant|restaurants} for a given identifier.
 9   *
10   * @param identifier - Where we should look for restaurants.
11   * @returns A list of all {@link Restaurant|restaurants} for a given identifier.
12   *
13   * @example
14   * const restaurants = await getRestaurantsFrom("bordeaux");
15   *
16   * for (const restaurant of restaurants) {
17   *   console.log(restaurant.title, restaurant.address);
18   * }
19   *
20   * @example
21   * const feeds = await getFeeds();
22   * const restaurants = await getRestaurantsFrom(feeds[0].identifier);
23   * // ...
24   */
25  export async function getRestaurantsFrom(identifier: string): Promise<Array<Restaurant>> {
26    const request = new HttpRequest.Builder(BASE_URL + `${identifier}/externe/crous-${identifier}.min.json`).build();
27    const response = await send(request);
28  
29    let content = await response.toString();
30    content = content.replaceAll(/[\u0000-\u001F]/g, "");
31  
32    const { restaurants } = JSON.parse(content) as {
33      restaurants: Array<definitions.restaurant>;
34    };
35  
36    return restaurants.map((restaurant) => deserialize(Restaurant, restaurant));
37  };