Created
April 7, 2025 09:58
-
-
Save cuongboi/6b41d9b98ae2df32bdff462d4118b3ca to your computer and use it in GitHub Desktop.
Nextjs Router Decorator Example Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { injectable } from "nextjs-route-decorator"; | |
import type { RegisterUser, Users, User } from "./user.schema"; | |
@injectable() | |
export class UserService { | |
async getUsers(): Promise<Users> { | |
return [ | |
{ | |
id: "1", | |
username: "user1", | |
email: "[email protected]", | |
}, | |
{ | |
id: "2", | |
username: "user2", | |
email: "[email protected]", | |
}, | |
]; | |
} | |
async registerUser(user: RegisterUser): Promise<User> { | |
return { | |
id: Math.random().toString(36).substring(2, 15), | |
username: user.username, | |
email: user.email, | |
}; | |
} | |
async getUserById(id: string): Promise<User | null> { | |
const users = await this.getUsers(); | |
return users.find((user) => user.id === id) || null; | |
} | |
async updateUser( | |
id: string, | |
user: Partial<RegisterUser> | |
): Promise<User | null> { | |
const users = await this.getUsers(); | |
const existingUser = users.find((u) => u.id === id); | |
if (existingUser) { | |
return { ...existingUser, ...user }; | |
} | |
return null; | |
} | |
async deleteUser(id: string): Promise<boolean> { | |
const users = await this.getUsers(); | |
const index = users.findIndex((user) => user.id === id); | |
if (index !== -1) { | |
users.splice(index, 1); | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment