Fake API
https://jsonplaceholder.typicode.com/posts
基本使用
控制行为
// 默认
fetch("url", {cache: "force-cache"});
// 不缓存
fetch("url", {cache: "no-store"});
// 定时刷新 s
fetch("url", {revalidate:3600});
不使用API
基本使用
// src/lib/data.js
// TEMPORARY DATA
// 后面可以用数据库链接取代
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
];
const posts = [
{ id: 1, title: "Post 1", body: "......", userId: 1 },
{ id: 2, title: "Post 2", body: "......", userId: 1 },
{ id: 3, title: "Post 3", body: "......", userId: 2 },
{ id: 4, title: "Post 4", body: "......", userId: 2 },
];
MongoDB
安装mongodb或使用云
略
在.env.xxx中配置mongodb环境变量
在nextjs项目中安装mongodb或mongoose
创建数据库链接函数
// /lib/utils.js
import mongoose from "mongoose"
// 防止重复链接
const connection = {};
export const connectToDb = async () => {
try {
if(connection.isConnected) {
console.log("Using existing connection");
return;
}
const db = await mongoose.connect(process.env.MONGO);
connection.isConnected = db.connections[0].readyState;
} catch (error) {
console.log(error);
throw new Error(error);
}
};
创建模型文件
// /lib/model.js
import mongoose from "mongoose";
const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true, // 必须
unique: true, // 唯一
min: 3, // 长度约束
max: 20,
},
email: {
type: String,
required: true,
unique: true,
max: 50,
},
password: {
type: String,
},
img: {
type: String,
},
isAdmin: {
type: Boolean,
default: false, // 默认值
},
},
{ timestamps: true }// 自动添加时间戳
// 字段为 createdAt: yyyy-mm-ddThh:mm:ss.mmm+00:00
);
const postSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
desc: {
type: String,
required: true,
},
img: {
type: String,
},
userId: {
type: String,
required: true,
},
slug: {
type: String,
required: true,
unique: true,
},
},
{ timestamps: true }
);
// 数据库中如果有model则使用数据库中的
export const User = mongoose.models?.User || mongoose.model("User", userSchema);
export const Post = mongoose.models?.Post || mongoose.model("Post", postSchema);
注意mongodb数据库中会默认添加_id字段,这也是findbyid所检索的字段
使用数据库
find/findOne/findById/findByIdAndDelete
noStore用于避免缓存
// data.js
import { Post, User } from "./models";
import { connectToDb } from "./utils";
import { unstable_noStore as noStore } from "next/cache";
// TEMPORARY DATA
// const users = [
// { id: 1, name: "John" },
// { id: 2, name: "Jane" },
// ];
// const posts = [
// { id: 1, title: "Post 1", body: "......", userId: 1 },
// { id: 2, title: "Post 2", body: "......", userId: 1 },
// { id: 3, title: "Post 3", body: "......", userId: 2 },
// { id: 4, title: "Post 4", body: "......", userId: 2 },
// ];
export const getPosts = async () => {
try {
connectToDb();
const posts = await Post.find();
return posts;
} catch (err) {
console.log(err);
throw new Error("Failed to fetch posts!");
}
};
export const getPost = async (slug) => {
try {
connectToDb();
const post = await Post.findOne({ slug });
return post;
} catch (err) {
console.log(err);
throw new Error("Failed to fetch post!");
}
};
export const getUser = async (id) => {
noStore();
try {
connectToDb();
const user = await User.findById(id);
return user;
} catch (err) {
console.log(err);
throw new Error("Failed to fetch user!");
}
};
export const getUsers = async () => {
try {
connectToDb();
const users = await User.find();
return users;
} catch (err) {
console.log(err);
throw new Error("Failed to fetch users!");
}
};
其他说明
通常fetch同一个接口或使用数据库获取同一数据多次不会重复执行。