-
Notifications
You must be signed in to change notification settings - Fork 666
/
getCategories.ts
49 lines (38 loc) · 1.32 KB
/
getCategories.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
import { getBaseUrl } from '#/lib/getBaseUrl';
import { notFound } from 'next/navigation';
import type { Category } from './category';
// `server-only` guarantees any modules that import code in file
// will never run on the client. Even though this particular api
// doesn't currently use sensitive environment variables, it's
// good practise to add `server-only` preemptively.
import 'server-only';
export async function getCategories({ parent }: { parent?: string } = {}) {
const res = await fetch(
`${getBaseUrl()}/api/categories${parent ? `?parent=${parent}` : ''}`,
);
if (!res.ok) {
// Render the closest `error.js` Error Boundary
throw new Error('Something went wrong!');
}
const categories = (await res.json()) as Category[];
if (categories.length === 0) {
// Render the closest `not-found.js` Error Boundary
notFound();
}
return categories;
}
export async function getCategory({ slug }: { slug: string }) {
const res = await fetch(
`${getBaseUrl()}/api/categories${slug ? `?slug=${slug}` : ''}`,
);
if (!res.ok) {
// Render the closest `error.js` Error Boundary
throw new Error('Something went wrong!');
}
const category = (await res.json()) as Category;
if (!category) {
// Render the closest `not-found.js` Error Boundary
notFound();
}
return category;
}