-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextjs-api-route.ts
More file actions
101 lines (84 loc) · 2.36 KB
/
nextjs-api-route.ts
File metadata and controls
101 lines (84 loc) · 2.36 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
/**
* Next.js API Route Example
*
* Place this file in: pages/api/oil-prices.ts (Pages Router)
* Or: app/api/oil-prices/route.ts (App Router - adjust export syntax)
*/
import type { NextApiRequest, NextApiResponse } from 'next';
import { OilPriceAPI, OilPriceAPIError } from 'oilpriceapi';
// Initialize client outside handler for connection reuse
const client = new OilPriceAPI({
apiKey: process.env.OIL_PRICE_API_KEY!,
retries: 3,
timeout: 10000
});
type SuccessResponse = {
success: true;
data: any;
cached?: boolean;
};
type ErrorResponse = {
success: false;
error: string;
statusCode?: number;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<SuccessResponse | ErrorResponse>
) {
// Only allow GET requests
if (req.method !== 'GET') {
return res.status(405).json({
success: false,
error: 'Method not allowed'
});
}
try {
const { commodity, period, type = 'latest' } = req.query;
// Set cache headers (cache for 5 minutes)
res.setHeader('Cache-Control', 'public, s-maxage=300, stale-while-revalidate=600');
if (type === 'latest') {
const prices = await client.getLatestPrices({
commodity: commodity as string | undefined
});
return res.status(200).json({
success: true,
data: prices
});
}
if (type === 'historical') {
const prices = await client.getHistoricalPrices({
commodity: commodity as string | undefined,
period: period as 'past_week' | 'past_month' | 'past_year' | undefined
});
return res.status(200).json({
success: true,
data: prices
});
}
if (type === 'commodities') {
const response = await client.getCommodities();
return res.status(200).json({
success: true,
data: response.commodities
});
}
return res.status(400).json({
success: false,
error: 'Invalid type parameter. Use: latest, historical, or commodities'
});
} catch (error) {
console.error('Oil Price API Error:', error);
if (error instanceof OilPriceAPIError) {
return res.status(error.statusCode || 500).json({
success: false,
error: error.message,
statusCode: error.statusCode
});
}
return res.status(500).json({
success: false,
error: 'Internal server error'
});
}
}