async function testAPI() {
try {
const response = await fetch("http://localhost:3000/api/movies", {
method: "GET",
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (error) {
console.error('Error fetching API:', error);
return [];
}
}
MongoDB에 데이터를 패칭하는 법
// lib/fetchAndInsert.ts
import fetch from 'node-fetch';
import clientPromise from './mongodb';
async function fetchExternalData(apiUrl: string) {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`Failed to fetch data from ${apiUrl}: ${response.statusText}`)
}
const data = await response.json();
return data;
}
async function insertDataToMongoDB(data: any) {
const client = await clientPromise;
const db = client.db('sample_mflix');
const collection = db.collection('nomad');
const result = await collection.insertMany(data);
return result;
}
async function fetchDataAndInsertToMongoDB(apiUrl: string) {
try {
const data = await fetchExternalData(apiUrl);
console.log('Data fetched from API: ', data);
const result = await insertDataToMongoDB(data);
console.log('Data inserted to MongoDB: ', result);
} catch (error) {
console.error("Error fetching data and inserting to MongoDB: ", error);
}
}
export default fetchDataAndInsertToMongoDB;
// app/api/fetch-and-insert/route.ts
import { NextRequest, NextResoponse } from "next/server";
import clientPromise from '../../../lib/mongodb';
export async function GET (request: NextRequest) {
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
try {
await fetchDataAndInsertToMongoDB(apiUrl);
return NextResponse.json({ message: "데이터 패치 및 삽입 완료" });
} catch(error) {
return NextResponse.json({ message: "데이터 패치 및 삽입 실패", error: error.message });
}
}
// app/(home)/page.tsx
async function testAPI() {
try {
const response = await fetch("http://localhost:3000/api/fetch-and-insert", {
method: "GET",
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (error) {
console.error("Error fetching API: ", error);
return [];
}
}
데이터 패칭하는 법(캐싱)
const getData = async() => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
if (!response.ok) {
throw new Error("Something went wrong!");
}
return response.json();
}
데이터 캐싱 하지않는 법
const getData = async() => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
cache: 'no-cache'});
if (!response.ok) {
throw new Error("Something went wrong!");
}
return response.json();
}
데이터 캐싱 유효기간 설정
const getData = async() => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
next: { revalidate: 3600 });
if (!response.ok) {
throw new Error("Something went wrong!");
}
return response.json();
}