https://github.com/arjuncodess/rest-apis-in-next.js-14
https://github.com/arjuncodess/rest-apis-in-next.js-14
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/arjuncodess/rest-apis-in-next.js-14
- Owner: ArjunCodess
- Created: 2024-06-06T14:46:12.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-06-11T07:08:40.000Z (about 1 year ago)
- Last Synced: 2025-02-08T16:46:31.866Z (5 months ago)
- Language: TypeScript
- Size: 73.2 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Building REST APIs in Next.js 14
[Course link](https://youtu.be/aEFkWxUNAVc)---
## Sample connectToDB() Function
```ts
import mongoose from 'mongoose';const MONGODB_URI = process.env.MONGODB_URI;
export default async function connectToDB() {
const connectionState = mongoose.connection.readyState;if (connectionState === 1) {
console.log("Already connected.");
return;
} else if (connectionState === 2) {
console.log("Connecting...");
return;
}try {
mongoose.connect(MONGODB_URI!, {
dbName: 'restapis-next14',
bufferCommands: true,
});console.log("Connected");
}catch (error: any) {
console.log("Error: ", error);
throw new Error("Error: ", error);
}
}
```---
## Sample Schema Code - User
```ts
import { Schema, model, models } from "mongoose";const UserSchema = new Schema(
{
email: { type: "string", required: true, unique: true },
username: { type: "string", required: true, unique: true },
password: { type: "string", required: true },
},
{
timestamps: true,
}
)const User = models.User || model("User", UserSchema);
export default User;
```---
## Get id(userId- automatically generated by MongoDB) and check if it's valid
```ts
const ObjectId = require("mongoose").Types.ObjectId;if (!Types.ObjectId.isValid(userId)) return new NextResponse(JSON.stringify({ message: "Invalid userId" }), { status: 400 })
```---
## Get data from URL using "?userId=something" notation
```ts
const { searchParams } = new URL(request.url);
const userId = searchParams.get("userId");
```---
## Reference of another Schema in a separate Schema
```ts
const CategorySchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: "User" }
})
```---
## Create a Schema which is dependent on another Schema
```ts
const user = await User.findById(userId);const newCategory = new Category({
title,
user: new Types.ObjectId(userId),
})
```---
## Get data using Dynamic Link (Params)
```ts
export const PATCH = async (context: { params: any }) => {
const categoryId = context.params.category;
}
```---
## Get if the category is present in the database and is linked to the user
```ts
const category = await User.findOne({ _id: categoryId, user: userId });
```---
## findByIdAndUpdate usage example
```ts
const updatedBlog = await Blog.findByIdAndUpdate(
blogId,
{ title, description },
{ new: true }
);
```---
## Implementing search functionality
```ts
const filter: any = {
user: new Types.ObjectId(userId),
category: new Types.ObjectId(categoryId),
}// check if the keyword exists in the title or the description
if (searchKeywords) {
filter.$or = [
{
title: { $regex: searchKeywords, $options: "i" },
// i => means search for both lowercase and uppercase
},
{
description: { $regex: searchKeywords, $options: "i" },
}
]
}
```---
## Use of createdAt method with $gte and $lte and other options
```ts
if (startDate && endDate) {
filter.createdAt = {
$gte: new Date(startDate), // greater than equal to start date
$lte: new Date(endDate), // less than equal to end date
}
} else if (startDate) {
filter.createdAt = {
$gte: new Date(startDate), // greater than equal to start date
}
} else if (endDate) {
filter.createdAt = {
$lte: new Date(endDate), // less than equal to end date
}
}const blogs = await Blog.find(filter)
.sort({ createdAt: desc ? 'desc' : 'asc' })
.skip(skip)
.limit(limit);
```---