forked from mongodb/docs-sample-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
518 lines (450 loc) · 13.8 KB
/
api.ts
File metadata and controls
518 lines (450 loc) · 13.8 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import { Movie, MoviesApiResponse } from '../types/movie';
/**
* API configuration and helper functions
*/
const API_BASE_URL = process.env.API_URL || 'http://localhost:3001';
/**
* Fetches movies from the Express API with pagination support
* This function runs on the server during SSR
*/
export async function fetchMovies(
limit: number = 20,
skip: number = 0
): Promise<{ movies: Movie[]; hasNextPage: boolean; hasPrevPage: boolean }> {
try {
// Request one extra movie to check if there's a next page
const requestLimit = Math.min(limit + 1, 100);
const response = await fetch(`${API_BASE_URL}/api/movies?limit=${requestLimit}&skip=${skip}`, {
next: { revalidate: 300 }, // Revalidate every 5 minutes
});
if (!response.ok) {
throw new Error(`Failed to fetch movies: ${response.status}`);
}
const result: MoviesApiResponse = await response.json();
if (!result.success) {
throw new Error('API returned error response');
}
const hasNextPage = result.data.length > limit;
const movies = hasNextPage ? result.data.slice(0, limit) : result.data;
const hasPrevPage = skip > 0;
return {
movies,
hasNextPage,
hasPrevPage
};
} catch (error) {
console.error('Error fetching movies:', error);
// In development, throw the error to help with debugging
if (process.env.NODE_ENV === 'development') {
throw error;
}
// In production, return empty result with logged error to prevent page crash
return {
movies: [],
hasNextPage: false,
hasPrevPage: false
};
}
}
/**
* Fetch a single movie by ID
*/
export async function fetchMovieById(id: string): Promise<Movie | null> {
try {
// Validate the ID format (basic validation)
if (!id || id.length !== 24) {
console.warn('Invalid movie ID format:', id);
return null;
}
const response = await fetch(`${API_BASE_URL}/api/movies/${id}`, {
next: { revalidate: 300 },
});
if (!response.ok) {
console.warn(`Failed to fetch movie ${id}: ${response.status}`);
return null;
}
const result = await response.json();
if (!result.success) {
console.warn('API returned error response for movie:', id);
return null;
}
return result.data;
} catch (error) {
console.error('Error fetching movie:', error);
return null;
}
}
/**
* Update a movie by ID
*/
export async function updateMovie(id: string, updateData: Partial<Movie>): Promise<{ success: boolean; error?: string }> {
try {
// Validate the ID format
if (!id || id.length !== 24) {
return { success: false, error: 'Invalid movie ID format' };
}
// Remove the _id field from update data if present
const { _id, ...dataToUpdate } = updateData;
const response = await fetch(`${API_BASE_URL}/api/movies/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dataToUpdate),
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.message || result.error?.message || `Failed to update movie: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.message || result.error?.message || 'API returned error response'
};
}
return { success: true };
} catch (error) {
console.error('Error updating movie:', error);
return {
success: false,
error: 'Network error occurred while updating movie'
};
}
}
/**
* Delete a movie by ID
*/
export async function deleteMovie(id: string): Promise<{ success: boolean; error?: string }> {
try {
// Validate the ID format
if (!id || id.length !== 24) {
return { success: false, error: 'Invalid movie ID format' };
}
const response = await fetch(`${API_BASE_URL}/api/movies/${id}`, {
method: 'DELETE',
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.message || result.error?.message || `Failed to delete movie: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.message || result.error?.message || 'API returned error response'
};
}
return { success: true };
} catch (error) {
console.error('Error deleting movie:', error);
return {
success: false,
error: 'Network error occurred while deleting movie'
};
}
}
/**
* Create a new movie
*/
export async function createMovie(movieData: Omit<Movie, '_id'>): Promise<{ success: boolean; error?: string; movieId?: string }> {
try {
const response = await fetch(`${API_BASE_URL}/api/movies`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(movieData),
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.message || result.error?.message || `Failed to create movie: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.message || result.error?.message || 'API returned error response'
};
}
return {
success: true,
movieId: result.data._id || result.data.insertedId
};
} catch (error) {
console.error('Error creating movie:', error);
return {
success: false,
error: 'Network error occurred while creating movie'
};
}
}
/**
* Create multiple movies in a batch operation
*/
export async function createMoviesBatch(moviesData: Omit<Movie, '_id'>[]): Promise<{ success: boolean; error?: string; insertedCount?: number; insertedIds?: string[] }> {
try {
const response = await fetch(`${API_BASE_URL}/api/movies/batch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(moviesData),
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.message || result.error?.message || `Failed to create movies: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.message || result.error?.message || 'API returned error response'
};
}
return {
success: true,
insertedCount: result.data.insertedCount,
insertedIds: result.data.insertedIds ? Object.values(result.data.insertedIds) : []
};
} catch (error) {
console.error('Error creating movies batch:', error);
return {
success: false,
error: 'Network error occurred while creating movies'
};
}
}
/**
* Delete multiple movies in a batch operation
*/
export async function deleteMoviesBatch(movieIds: string[]): Promise<{ success: boolean; error?: string; deletedCount?: number }> {
try {
// Create filter to match the movie IDs
// Note: The server will handle ObjectId conversion
const filter = {
_id: {
$in: movieIds
}
};
const response = await fetch(`${API_BASE_URL}/api/movies`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ filter }),
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.message || result.error?.message || `Failed to delete movies: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.message || result.error?.message || 'API returned error response'
};
}
return {
success: true,
deletedCount: result.data.deletedCount
};
} catch (error) {
console.error('Error deleting movies batch:', error);
return {
success: false,
error: 'Network error occurred while deleting movies'
};
}
}
/**
* Update multiple movies in a batch operation
*/
export async function updateMoviesBatch(movieIds: string[], updateData: Partial<Movie>): Promise<{ success: boolean; error?: string; matchedCount?: number; modifiedCount?: number }> {
try {
// Create filter to match the movie IDs
// Note: The server will handle ObjectId conversion
const filter = {
_id: {
$in: movieIds
}
};
const response = await fetch(`${API_BASE_URL}/api/movies`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ filter, update: updateData }),
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.message || result.error?.message || `Failed to update movies: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.message || result.error?.message || 'API returned error response'
};
}
return {
success: true,
matchedCount: result.data.matchedCount,
modifiedCount: result.data.modifiedCount
};
} catch (error) {
console.error('Error updating movies batch:', error);
return {
success: false,
error: 'Network error occurred while updating movies'
};
}
}
/**
* Search movies using MongoDB Search across multiple fields with pagination support
*/
export async function searchMovies(searchParams: {
plot?: string;
fullplot?: string;
directors?: string;
writers?: string;
cast?: string;
limit?: number;
skip?: number;
search_operator?: 'must' | 'should' | 'mustNot' | 'filter';
}): Promise<{ success: boolean; error?: string; movies?: Movie[]; hasNextPage?: boolean; hasPrevPage?: boolean; totalCount?: number }> {
try {
// Build query parameters
const limit = searchParams.limit || 20;
const skip = searchParams.skip || 0;
const queryParams = new URLSearchParams();
if (searchParams.plot) queryParams.append('plot', searchParams.plot);
if (searchParams.fullplot) queryParams.append('fullplot', searchParams.fullplot);
if (searchParams.directors) queryParams.append('directors', searchParams.directors);
if (searchParams.writers) queryParams.append('writers', searchParams.writers);
if (searchParams.cast) queryParams.append('cast', searchParams.cast);
queryParams.append('limit', limit.toString());
queryParams.append('skip', skip.toString());
if (searchParams.search_operator) queryParams.append('search_operator', searchParams.search_operator);
const response = await fetch(`${API_BASE_URL}/api/movies/search?${queryParams}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.message || result.error?.message || `Failed to search movies: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.message || result.error?.message || 'API returned error response'
};
}
const responseData = result.data || {};
const movies = responseData.movies || [];
const totalCount = responseData.totalCount || 0;
const hasNextPage = skip + limit < totalCount;
const hasPrevPage = skip > 0;
return {
success: true,
movies,
hasNextPage,
hasPrevPage,
totalCount
};
} catch (error) {
console.error('Error searching movies:', error);
return {
success: false,
error: 'Network error occurred while searching movies'
};
}
}
/**
* Search movies using MongoDB Vector Search to find movies with similar plots
*/
export async function vectorSearchMovies(searchParams: {
q: string;
limit?: number;
}): Promise<{ success: boolean; error?: string; movies?: Movie[]; results?: any[] }> {
try {
const limit = searchParams.limit || 10;
const queryParams = new URLSearchParams();
queryParams.append('q', searchParams.q);
queryParams.append('limit', limit.toString());
const response = await fetch(`${API_BASE_URL}/api/movies/vector-search?${queryParams}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
error: result.error || `Failed to perform vector search: ${response.status}`
};
}
if (!result.success) {
return {
success: false,
error: result.error || 'API returned error response'
};
}
// Transform VectorSearchResult objects to Movie objects for backend compatibility
const movies: Movie[] = (result.data || []).map((item: any) => {
// Convert VectorSearchResult to Movie format
return {
_id: item._id || item.id, // Handle both _id (Python) and id (Java) field names
title: item.title || '',
plot: item.plot || '',
poster: item.poster,
year: item.year,
genres: item.genres || [],
directors: item.directors || [],
cast: item.cast || [],
// Add default values for fields not included in VectorSearchResult
fullplot: undefined,
released: undefined,
runtime: undefined,
writers: [],
countries: [],
languages: [],
rated: undefined,
awards: undefined,
imdb: undefined,
tomatoes: undefined,
metacritic: undefined,
type: undefined
} as Movie;
});
return {
success: true,
movies,
results: result.data || []
};
} catch (error) {
console.error('Error performing vector search:', error);
return {
success: false,
error: 'Network error occurred while performing vector search'
};
}
}