Create src/lib/grabber/search.functions.ts

#2
Files changed (1) hide show
  1. src/lib/grabber/search.functions.ts +37 -0
src/lib/grabber/search.functions.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createServerFn } from '@tanstack/start';
2
+ import fetch from 'node-fetch'; // Use bun's native fetch in production if preferred
3
+ import { SiteConfig, NormalizedPost, getByPath } from './sites';
4
+
5
+ export const searchPosts = createServerFn(async ({ args }) => {
6
+ const { siteId, tags, page, limit } = args;
7
+ const config = getByPath(siteId);
8
+
9
+ if (!config) return { error: 'Site not found' };
10
+
11
+ const url = new URL(`${config.baseUrl}${config.searchPath}`);
12
+ Object.entries(config.params).forEach(([key, param]) => {
13
+ url.searchParams.set(key, tags || page?.toString() || limit?.toString());
14
+ });
15
+
16
+ try {
17
+ const response = await fetch(url.toString(), { headers: config.headers });
18
+ if (!response.ok) throw new Error('Failed to fetch');
19
+ const data = await response.json();
20
+ const rawPosts = data[config.postsPath] || [];
21
+
22
+ const posts: NormalizedPost[] = rawPosts.map(post => ({
23
+ id: post[config.fields.id],
24
+ previewUrl: post[config.fields.previewUrl],
25
+ fileUrl: post[config.fields.fileUrl],
26
+ ext: post[config.fields.ext],
27
+ tags: post[config.fields.tags] as string[],
28
+ source: post[config.fields.source],
29
+ rating: post[config.fields.rating],
30
+ score: Number(post[config.fields.score]),
31
+ }));
32
+
33
+ return { posts };
34
+ } catch (e) {
35
+ return { error: e instanceof Error ? e.message : 'Unknown error' };
36
+ }
37
+ });