xxxxxxxxxx
// Import the required modules
import { connectToDatabase } from '../lib/mongodb';
import { revalidatePath, redirect } from 'next/cache';
// Create a server function to create a new post
export async function createPost(formData) {
'use server';
// Get the title and content from the form data
const { title, content } = formData;
// Validate the input
if (!title || !content) {
throw new Error('Missing title or content');
}
// Connect to the database
const { db } = await connectToDatabase();
// Insert a new post into the posts collection
await db.collection('posts').insertOne({ title, content });
// Revalidate the home page to show the new post
revalidatePath('/');
// Redirect the user to the home page
redirect('/');
}
xxxxxxxxxx
// Import the required modules
import { useState } from 'react';
import { invoke } from 'next/server';
// Create a component that renders a form for creating a new post
export default function CreatePostForm() {
// Use state hooks to store the title and content of the post
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
// Define a function that handles the form submission
const handleSubmit = async (event) => {
// Prevent the default behavior of the form
event.preventDefault();
// Invoke the createPost server function with the title and content as data
await invoke('createPost', { title, content });
// Clear the form fields
setTitle('');
setContent('');
};
// Return the JSX element that renders the form
return (
<form onSubmit={handleSubmit}>
<label htmlFor="title">Title</label>
<input
id="title"
type="text"
value={title}
onChange={(event) => setTitle(event.target.value)}
required
/>
<label htmlFor="content">Content</label>
<textarea
id="content"
value={content}
onChange={(event) => setContent(event.target.value)}
required
/>
<button type="submit">Create Post</button>
</form>
);
}
xxxxxxxxxx
// Import the required modules
import { MongoClient } from 'mongodb';
// Define the connection URL and the database name
const url = 'mongodb://localhost:27017';
const dbName = 'blog';
// Create a global variable to store the database connection
let cachedDb = null;
// Create a helper function that connects to the database and returns the database object
export async function connectToDatabase() {
// Check if the database connection is cached
if (cachedDb) {
// Return the cached connection
return cachedDb;
}
// Create a new connection to the database
const client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Select the database
const db = await client.db(dbName);
// Cache the database connection
cachedDb = db;
// Return the database object
return db;
}
xxxxxxxxxx
// Import the required modules
import { connectToDatabase } from '../lib/mongodb';
import { revalidatePath, redirect } from 'next/cache';
// Create a server function to read all the posts
export async function readPosts() {
'use server';
// Connect to the database
const db = await connectToDatabase();
// Find all the posts in the posts collection and return them as a JSON array
return await db.collection('posts').find().toArray();
}
// Create a server function to update a post
export async function updatePost(formData) {
'use server';
// Get the id, title, and content from the form data
const { id, title, content } = formData;
// Validate the input
if (!id || !title || !content) {
throw new Error('Missing id, title, or content');
}
// Connect to the database
const db = await connectToDatabase();
// Update the post with the given id in the posts collection
await db.collection('posts').updateOne({ _id: id }, { $set: { title, content } });
// Revalidate the home page to show the updated post
revalidatePath('/');
// Redirect the user to the home page
redirect('/');
}
// Create a server function to delete a post
export async function deletePost(formData) {
'use server';
// Get the id from the form data
const { id } = formData;
// Validate the input
if (!id) {
throw new Error('Missing id');
}
// Connect to the database
const db = await connectToDatabase();
// Delete the post with the given id from the posts collection
await db.collection('posts').deleteOne({ _id: id });
// Revalidate the home page to remove the deleted post
revalidatePath('/');
// Redirect the user to the home page
redirect('/');
}