feat: implement order and product models, services, and routes with validation

This commit is contained in:
2026-01-13 00:03:48 +03:00
parent 8f2477b25e
commit da428f83bc
13 changed files with 505 additions and 5 deletions
+78
View File
@@ -0,0 +1,78 @@
import { Schema, model } from "mongoose";
import { v4 as uuidv4 } from "uuid";
export type OrderStatus = "created" | "paid" | "cancelled";
export interface OrderItem {
productId: string;
quantity: number;
unitPrice: number;
}
export interface OrderDocument {
_id: string;
userId: string;
items: OrderItem[];
total: number;
status: OrderStatus;
createdAt: Date;
updatedAt: Date;
}
const orderItemSchema = new Schema<OrderItem>(
{
productId: {
type: String,
required: true,
},
quantity: {
type: Number,
required: true,
min: 1,
},
unitPrice: {
type: Number,
required: true,
min: 1,
},
},
{ _id: false },
);
const orderSchema = new Schema<OrderDocument>(
{
_id: {
type: String,
default: uuidv4,
},
userId: {
type: String,
required: true,
index: true,
},
items: {
type: [orderItemSchema],
required: true,
validate: {
validator: (items: OrderItem[]) => items.length > 0,
message: "Order must contain at least one item",
},
},
total: {
type: Number,
required: true,
min: 1,
},
status: {
type: String,
enum: ["created", "paid", "cancelled"],
default: "created",
index: true,
},
},
{
timestamps: true,
},
);
export const OrderModel = model<OrderDocument>("Order", orderSchema);
+40
View File
@@ -0,0 +1,40 @@
import { Schema, model } from "mongoose";
import { v4 as uuidv4 } from "uuid";
export interface ProductDocument {
_id: string;
name: string;
price: number; // cents
stock: number;
createdAt: Date;
updatedAt: Date;
}
const productSchema = new Schema<ProductDocument>(
{
_id: {
type: String,
default: uuidv4,
},
name: {
type: String,
required: true,
trim: true,
},
price: {
type: Number,
required: true,
min: 1,
},
stock: {
type: Number,
required: true,
min: 0,
},
},
{
timestamps: true,
},
);
export const ProductModel = model<ProductDocument>("Product", productSchema);
+43
View File
@@ -0,0 +1,43 @@
import { Schema, model } from "mongoose";
import { v4 as uuidv4 } from "uuid";
export type UserRole = "admin" | "customer";
export interface UserDocument {
_id: string;
email: string;
passwordHash: string;
role: UserRole;
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema<UserDocument>(
{
_id: {
type: String,
default: uuidv4,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
index: true,
},
passwordHash: {
type: String,
required: true,
},
role: {
type: String,
enum: ["admin", "customer"],
default: "customer",
},
},
{
timestamps: true,
},
);
export const UserModel = model<UserDocument>("User", userSchema);