1 import { RegionCountryDTO } from "@medusajs/types"
2 import { StaticCountry } from "../../../../lib/data/countries"
3 import { jsonResponse } from "../../../../lib/json-response"
4
5 const acceptedOrderKeys = ["name", "iso_2"]
6
7 /**
8 * Since countries cannot be retrieved from the API, we need to create a hook
9 * that can be used to filter and sort the static list of countries.
10 */
11 export const useCountries = ({
12 countries,
13 q,
14 order = "name",
15 limit,
16 offset = 0,
17 }: {
18 countries: StaticCountry[]
19 limit: number
20 offset?: number
21 order?: string
22 q?: string
23 }) => {
24 const data = countries.slice(offset, offset + limit)
25
26 if (order) {
27 const direction = order.startsWith("-") ? -1 : 1
28 const key = order.replace("-", "")
29
30 if (!acceptedOrderKeys.includes(key)) {
31 console.log(`The key ${key} is not a valid order key`)
32 throw jsonResponse(`The key ${key} is not a valid order key`, 500)
33 }
34
35 const sortKey = key as keyof RegionCountryDTO
36
37 data.sort((a, b) => {
38 if (a[sortKey] === null && b[sortKey] === null) {
39 return 0
40 }
41 if (a[sortKey] === null) {
42 return direction
43 }
44 if (b[sortKey] === null) {
45 return -direction
46 }
47 return a[sortKey]! > b[sortKey]! ? direction : -direction
48 })
49 }
50
51 if (q) {
52 const query = q.toLowerCase()
53 const results = countries.filter(
54 (c) =>
55 c.name.toLowerCase().includes(query) ||
56 c.iso_2.toLowerCase().includes(query)
57 )
58 return {
59 countries: results,
60 count: results.length,
61 }
62 }
63
64 return {
65 countries: data,
66 count: countries.length,
67 }
68 }