mirror of
https://git.meshkee.com/novintrades/website.git
synced 2026-08-11 20:50:58 +04:30
Initial commit: NovinTrades website monorepo.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "@novintrades/api",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/index.js",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:deploy": "prisma migrate deploy",
|
||||
"db:seed": "tsx prisma/seed.ts",
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1093.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1093.0",
|
||||
"@fastify/cors": "^11.1.0",
|
||||
"@fastify/multipart": "^10.1.0",
|
||||
"@prisma/client": "^6.16.2",
|
||||
"bcryptjs": "^3.0.2",
|
||||
"fastify": "^5.6.0",
|
||||
"zod": "^4.1.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/node": "^24.13.2",
|
||||
"prisma": "^6.16.2",
|
||||
"tsx": "^4.20.5",
|
||||
"typescript": "~5.9.2"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/** Brand category tree sourced from Categories.docx (hierarchy preserved). */
|
||||
export type CategoryNode = {
|
||||
name: string;
|
||||
children?: CategoryNode[];
|
||||
};
|
||||
|
||||
export const brandCategoryTree: CategoryNode[] = [
|
||||
{
|
||||
name: "Oil, Energy & Feedstocks",
|
||||
children: [
|
||||
{
|
||||
name: "Oil Products",
|
||||
children: [
|
||||
{
|
||||
name: "Fuels",
|
||||
children: [
|
||||
{ name: "Gasoline" },
|
||||
{ name: "Diesel (EN590)" },
|
||||
{ name: "Jet Fuel" },
|
||||
{ name: "Kerosene" },
|
||||
{ name: "LPG" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Industrial & Base Oils",
|
||||
children: [
|
||||
{ name: "Base Oil" },
|
||||
{ name: "Engine Oil" },
|
||||
{ name: "Hydraulic Oil" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Heavy & Residual Products",
|
||||
children: [
|
||||
{
|
||||
name: "Bitumen",
|
||||
children: [
|
||||
{ name: "Bitumen 60/70" },
|
||||
{ name: "Bitumen 80/100" },
|
||||
{ name: "Bitumen 40/50" },
|
||||
{ name: "VG 30" },
|
||||
{ name: "VG 40" },
|
||||
],
|
||||
},
|
||||
{ name: "Petroleum Coke" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Light Distillates & Solvents",
|
||||
children: [
|
||||
{ name: "Naphtha" },
|
||||
{
|
||||
name: "Solvents",
|
||||
children: [
|
||||
{ name: "White Spirit" },
|
||||
{ name: "Industrial Solvents" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Energy Products",
|
||||
children: [{ name: "Crude Oil" }, { name: "LNG" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Industrial and Consumer Materials",
|
||||
children: [
|
||||
{
|
||||
name: "Medical & Pharmaceutical",
|
||||
children: [
|
||||
{ name: "Medicines" },
|
||||
{ name: "Medical Equipment" },
|
||||
{ name: "Healthcare Products" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Textile & Apparel",
|
||||
children: [
|
||||
{ name: "Raw Textiles" },
|
||||
{ name: "Fabrics" },
|
||||
{ name: "Garments" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Materials & Crafted Goods",
|
||||
children: [
|
||||
{ name: "Titanium Dioxide" },
|
||||
{ name: "Carbon Black" },
|
||||
{ name: "Silica Powder" },
|
||||
{ name: "Timber & Paper" },
|
||||
{ name: "Leather" },
|
||||
],
|
||||
},
|
||||
{ name: "Handicrafts" },
|
||||
{
|
||||
name: "Technology & Innovation",
|
||||
children: [
|
||||
{ name: "AI Solutions" },
|
||||
{ name: "Smart Trade Platforms" },
|
||||
{ name: "Industrial Technologies" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Chemicals & Petrochemicals",
|
||||
children: [
|
||||
{ name: "Urea" },
|
||||
{ name: "Sulfur" },
|
||||
{ name: "Methanol" },
|
||||
{ name: "Paint & Coatings Materials" },
|
||||
{ name: "Industrial Chemicals" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Metals, Mining & Minerals",
|
||||
children: [
|
||||
{ name: "Iron & Steel" },
|
||||
{ name: "Non-Ferrous Metals" },
|
||||
{
|
||||
name: "Jewelry & Precious Stones",
|
||||
children: [
|
||||
{ name: "Gold Jewelry" },
|
||||
{ name: "Silver Jewelry" },
|
||||
{ name: "Precious Stones" },
|
||||
{ name: "Semi-Precious Stones" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Minerals",
|
||||
children: [
|
||||
{ name: "Potash" },
|
||||
{ name: "Limestone" },
|
||||
{ name: "Kaolinite" },
|
||||
{ name: "Feldspar" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Food Products",
|
||||
children: [
|
||||
{ name: "Dates" },
|
||||
{ name: "Saffron" },
|
||||
{ name: "Honey" },
|
||||
{ name: "Fruits" },
|
||||
{ name: "Palm Oil" },
|
||||
{ name: "Beverages" },
|
||||
{ name: "Confectionery" },
|
||||
{ name: "Low Sodium Salt" },
|
||||
{
|
||||
name: "Seafood & Aquaculture",
|
||||
children: [
|
||||
{ name: "Shrimp" },
|
||||
{ name: "Fish" },
|
||||
{ name: "Aquaculture Products" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Building Materials",
|
||||
children: [{ name: "Construction Stones" }],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,193 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "VerificationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CategoryScope" AS ENUM ('CONTENT', 'BRAND');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "User" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"passwordHash" TEXT NOT NULL,
|
||||
"name" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Category" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"scope" "CategoryScope" NOT NULL,
|
||||
"parentId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Category_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Blog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"abstract" TEXT,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"imageUrl" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"verificationStatus" "VerificationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"authorId" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Blog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "BlogCategory" (
|
||||
"blogId" TEXT NOT NULL,
|
||||
"categoryId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "BlogCategory_pkey" PRIMARY KEY ("blogId","categoryId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Reportage" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"businessOwner" TEXT NOT NULL,
|
||||
"abstract" TEXT,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"imageUrl" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"verificationStatus" "VerificationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"authorId" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Reportage_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ReportageCategory" (
|
||||
"reportageId" TEXT NOT NULL,
|
||||
"categoryId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "ReportageCategory_pkey" PRIMARY KEY ("reportageId","categoryId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Brand" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"abstract" TEXT,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"imageUrl" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"country" TEXT NOT NULL,
|
||||
"address" TEXT,
|
||||
"contacts" JSONB NOT NULL DEFAULT '[]',
|
||||
"verificationStatus" "VerificationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"authorId" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Brand_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "BrandCategory" (
|
||||
"brandId" TEXT NOT NULL,
|
||||
"categoryId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "BrandCategory_pkey" PRIMARY KEY ("brandId","categoryId")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Category_parentId_idx" ON "Category"("parentId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Category_scope_idx" ON "Category"("scope");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Category_scope_slug_key" ON "Category"("scope", "slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Blog_slug_key" ON "Blog"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Blog_authorId_idx" ON "Blog"("authorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Blog_verificationStatus_idx" ON "Blog"("verificationStatus");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "BlogCategory_categoryId_idx" ON "BlogCategory"("categoryId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Reportage_slug_key" ON "Reportage"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Reportage_authorId_idx" ON "Reportage"("authorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Reportage_verificationStatus_idx" ON "Reportage"("verificationStatus");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ReportageCategory_categoryId_idx" ON "ReportageCategory"("categoryId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Brand_slug_key" ON "Brand"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Brand_authorId_idx" ON "Brand"("authorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Brand_verificationStatus_idx" ON "Brand"("verificationStatus");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Brand_country_idx" ON "Brand"("country");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "BrandCategory_categoryId_idx" ON "BrandCategory"("categoryId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Category" ADD CONSTRAINT "Category_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "Category"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Blog" ADD CONSTRAINT "Blog_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BlogCategory" ADD CONSTRAINT "BlogCategory_blogId_fkey" FOREIGN KEY ("blogId") REFERENCES "Blog"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BlogCategory" ADD CONSTRAINT "BlogCategory_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Reportage" ADD CONSTRAINT "Reportage_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ReportageCategory" ADD CONSTRAINT "ReportageCategory_reportageId_fkey" FOREIGN KEY ("reportageId") REFERENCES "Reportage"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ReportageCategory" ADD CONSTRAINT "ReportageCategory_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Brand" ADD CONSTRAINT "Brand_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BrandCategory" ADD CONSTRAINT "BrandCategory_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "Brand"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BrandCategory" ADD CONSTRAINT "BrandCategory_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Brand" ADD COLUMN "galleryUrls" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Brand" ADD COLUMN "city" TEXT;
|
||||
@@ -0,0 +1,80 @@
|
||||
-- Merge duplicate categories that share the same slug across scopes,
|
||||
-- then drop scope so one Category table serves blog, reportage, and brand.
|
||||
|
||||
CREATE TEMP TABLE category_keepers AS
|
||||
SELECT DISTINCT ON (slug) id AS keeper_id, slug
|
||||
FROM "Category"
|
||||
ORDER BY slug, "createdAt" ASC, id ASC;
|
||||
|
||||
CREATE TEMP TABLE category_dupes AS
|
||||
SELECT c.id AS dupe_id, k.keeper_id
|
||||
FROM "Category" c
|
||||
JOIN category_keepers k ON k.slug = c.slug
|
||||
WHERE c.id <> k.keeper_id;
|
||||
|
||||
-- BlogCategory: remap to keeper when no conflict
|
||||
UPDATE "BlogCategory" bc
|
||||
SET "categoryId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "BlogCategory" x
|
||||
WHERE x."blogId" = bc."blogId"
|
||||
AND x."categoryId" = d.keeper_id
|
||||
);
|
||||
|
||||
DELETE FROM "BlogCategory" bc
|
||||
USING category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id;
|
||||
|
||||
-- ReportageCategory
|
||||
UPDATE "ReportageCategory" rc
|
||||
SET "categoryId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE rc."categoryId" = d.dupe_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "ReportageCategory" x
|
||||
WHERE x."reportageId" = rc."reportageId"
|
||||
AND x."categoryId" = d.keeper_id
|
||||
);
|
||||
|
||||
DELETE FROM "ReportageCategory" rc
|
||||
USING category_dupes d
|
||||
WHERE rc."categoryId" = d.dupe_id;
|
||||
|
||||
-- BrandCategory
|
||||
UPDATE "BrandCategory" bc
|
||||
SET "categoryId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandCategory" x
|
||||
WHERE x."brandId" = bc."brandId"
|
||||
AND x."categoryId" = d.keeper_id
|
||||
);
|
||||
|
||||
DELETE FROM "BrandCategory" bc
|
||||
USING category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id;
|
||||
|
||||
-- Point children of duplicates at the keeper
|
||||
UPDATE "Category" c
|
||||
SET "parentId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE c."parentId" = d.dupe_id;
|
||||
|
||||
DELETE FROM "Category" c
|
||||
USING category_dupes d
|
||||
WHERE c.id = d.dupe_id;
|
||||
|
||||
DROP INDEX IF EXISTS "Category_scope_slug_key";
|
||||
DROP INDEX IF EXISTS "Category_scope_idx";
|
||||
|
||||
ALTER TABLE "Category" DROP COLUMN "scope";
|
||||
|
||||
CREATE UNIQUE INDEX "Category_slug_key" ON "Category"("slug");
|
||||
|
||||
DROP TYPE "CategoryScope";
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,143 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
enum VerificationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
passwordHash String
|
||||
name String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
blogs Blog[]
|
||||
reportages Reportage[]
|
||||
brands Brand[]
|
||||
}
|
||||
|
||||
/// Shared categories for blog, reportage, and brand
|
||||
model Category {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
slug String @unique
|
||||
parentId String?
|
||||
parent Category? @relation("CategoryTree", fields: [parentId], references: [id], onDelete: SetNull)
|
||||
children Category[] @relation("CategoryTree")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
blogs BlogCategory[]
|
||||
reportages ReportageCategory[]
|
||||
brands BrandCategory[]
|
||||
|
||||
@@index([parentId])
|
||||
}
|
||||
|
||||
model Blog {
|
||||
id String @id @default(cuid())
|
||||
title String
|
||||
slug String @unique
|
||||
abstract String?
|
||||
content String @default("")
|
||||
imageUrl String?
|
||||
tags String[] @default([])
|
||||
verificationStatus VerificationStatus @default(PENDING)
|
||||
authorId String
|
||||
author User @relation(fields: [authorId], references: [id], onDelete: Restrict)
|
||||
categories BlogCategory[]
|
||||
publishedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([authorId])
|
||||
@@index([verificationStatus])
|
||||
}
|
||||
|
||||
model BlogCategory {
|
||||
blogId String
|
||||
categoryId String
|
||||
blog Blog @relation(fields: [blogId], references: [id], onDelete: Cascade)
|
||||
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([blogId, categoryId])
|
||||
@@index([categoryId])
|
||||
}
|
||||
|
||||
model Reportage {
|
||||
id String @id @default(cuid())
|
||||
title String
|
||||
slug String @unique
|
||||
businessOwner String
|
||||
abstract String?
|
||||
content String @default("")
|
||||
imageUrl String?
|
||||
tags String[] @default([])
|
||||
verificationStatus VerificationStatus @default(PENDING)
|
||||
authorId String
|
||||
author User @relation(fields: [authorId], references: [id], onDelete: Restrict)
|
||||
categories ReportageCategory[]
|
||||
publishedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([authorId])
|
||||
@@index([verificationStatus])
|
||||
}
|
||||
|
||||
model ReportageCategory {
|
||||
reportageId String
|
||||
categoryId String
|
||||
reportage Reportage @relation(fields: [reportageId], references: [id], onDelete: Cascade)
|
||||
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([reportageId, categoryId])
|
||||
@@index([categoryId])
|
||||
}
|
||||
|
||||
model Brand {
|
||||
id String @id @default(cuid())
|
||||
title String
|
||||
slug String @unique
|
||||
abstract String?
|
||||
content String @default("")
|
||||
imageUrl String?
|
||||
galleryUrls String[] @default([])
|
||||
tags String[] @default([])
|
||||
country String
|
||||
city String?
|
||||
address String?
|
||||
/// [{ type: "phone"|"email"|..., value: string }]
|
||||
contacts Json @default("[]")
|
||||
verificationStatus VerificationStatus @default(PENDING)
|
||||
authorId String
|
||||
author User @relation(fields: [authorId], references: [id], onDelete: Restrict)
|
||||
categories BrandCategory[]
|
||||
publishedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([authorId])
|
||||
@@index([verificationStatus])
|
||||
@@index([country])
|
||||
}
|
||||
|
||||
model BrandCategory {
|
||||
brandId String
|
||||
categoryId String
|
||||
brand Brand @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([brandId, categoryId])
|
||||
@@index([categoryId])
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
import {
|
||||
brandCategoryTree,
|
||||
type CategoryNode,
|
||||
} from "./data/brand-categories.js";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
function slugify(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 120);
|
||||
}
|
||||
|
||||
async function uniqueSlug(base: string): Promise<string> {
|
||||
let slug = slugify(base) || "category";
|
||||
let candidate = slug;
|
||||
let i = 2;
|
||||
while (await prisma.category.findUnique({ where: { slug: candidate } })) {
|
||||
candidate = `${slug}-${i}`;
|
||||
i += 1;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
async function insertTree(
|
||||
nodes: CategoryNode[],
|
||||
parentId: string | null = null,
|
||||
): Promise<number> {
|
||||
let count = 0;
|
||||
for (const node of nodes) {
|
||||
const slug = await uniqueSlug(node.name);
|
||||
const created = await prisma.category.create({
|
||||
data: {
|
||||
name: node.name,
|
||||
slug,
|
||||
parentId,
|
||||
},
|
||||
});
|
||||
count += 1;
|
||||
if (node.children?.length) {
|
||||
count += await insertTree(node.children, created.id);
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const passwordHash = await bcrypt.hash("admin123", 10);
|
||||
|
||||
const admin = await prisma.user.upsert({
|
||||
where: { email: "admin@novintrades.com" },
|
||||
update: {},
|
||||
create: {
|
||||
email: "admin@novintrades.com",
|
||||
name: "Admin",
|
||||
passwordHash,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.blogCategory.deleteMany();
|
||||
await prisma.reportageCategory.deleteMany();
|
||||
await prisma.brandCategory.deleteMany();
|
||||
await prisma.category.deleteMany();
|
||||
|
||||
const treeCount = await insertTree(brandCategoryTree);
|
||||
|
||||
console.log(`Seeded admin: ${admin.email}`);
|
||||
console.log(`Seeded ${treeCount} categories from Categories.docx hierarchy`);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import Fastify from "fastify";
|
||||
import cors from "@fastify/cors";
|
||||
import { prisma } from "./lib/prisma.js";
|
||||
import { healthRoutes } from "./routes/health.js";
|
||||
import { categoryRoutes } from "./routes/categories.js";
|
||||
import { blogRoutes } from "./routes/blogs.js";
|
||||
import { reportageRoutes } from "./routes/reportages.js";
|
||||
import { brandRoutes } from "./routes/brands.js";
|
||||
import { authRoutes } from "./routes/auth.js";
|
||||
import { uploadRoutes } from "./routes/uploads.js";
|
||||
|
||||
export async function buildApp() {
|
||||
const app = Fastify({
|
||||
logger: true,
|
||||
});
|
||||
|
||||
await app.register(cors, {
|
||||
origin: true,
|
||||
});
|
||||
|
||||
app.decorate("prisma", prisma);
|
||||
|
||||
await app.register(healthRoutes);
|
||||
await app.register(authRoutes, { prefix: "/api/auth" });
|
||||
await app.register(categoryRoutes, { prefix: "/api/categories" });
|
||||
await app.register(blogRoutes, { prefix: "/api/blogs" });
|
||||
await app.register(reportageRoutes, { prefix: "/api/reportages" });
|
||||
await app.register(brandRoutes, { prefix: "/api/brands" });
|
||||
await app.register(uploadRoutes, { prefix: "/api/uploads" });
|
||||
|
||||
app.addHook("onClose", async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyInstance {
|
||||
prisma: typeof prisma;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { buildApp } from "./app.js";
|
||||
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
const host = process.env.HOST ?? "0.0.0.0";
|
||||
|
||||
const app = await buildApp();
|
||||
|
||||
try {
|
||||
await app.listen({ port, host });
|
||||
} catch (error) {
|
||||
app.log.error(error);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export const MAX_IMAGE_BYTES = Number(
|
||||
process.env.MAX_IMAGE_BYTES ?? 250 * 1024,
|
||||
);
|
||||
|
||||
export function assertImageSize(bytes: number): void {
|
||||
if (bytes > MAX_IMAGE_BYTES) {
|
||||
const maxKb = Math.round(MAX_IMAGE_BYTES / 1024);
|
||||
throw Object.assign(
|
||||
new Error(`Image must be ${maxKb}KB or smaller`),
|
||||
{ statusCode: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
export const prisma = new PrismaClient();
|
||||
@@ -0,0 +1,87 @@
|
||||
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { assertImageSize } from "./limits.js";
|
||||
|
||||
function required(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (!value) {
|
||||
throw new Error(`Missing env ${name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
let client: S3Client | null = null;
|
||||
|
||||
function getClient(): S3Client {
|
||||
if (!client) {
|
||||
client = new S3Client({
|
||||
region: process.env.S3_REGION ?? "us-east-1",
|
||||
endpoint: required("S3_ENDPOINT"),
|
||||
forcePathStyle: true,
|
||||
credentials: {
|
||||
accessKeyId: required("S3_ACCESS_KEY"),
|
||||
secretAccessKey: required("S3_SECRET_KEY"),
|
||||
},
|
||||
});
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
function extensionFor(mime: string): string {
|
||||
switch (mime) {
|
||||
case "image/png":
|
||||
return "png";
|
||||
case "image/webp":
|
||||
return "webp";
|
||||
case "image/gif":
|
||||
return "gif";
|
||||
case "image/jpeg":
|
||||
case "image/jpg":
|
||||
default:
|
||||
return "jpg";
|
||||
}
|
||||
}
|
||||
|
||||
export async function uploadImageBuffer(input: {
|
||||
buffer: Buffer;
|
||||
contentType: string;
|
||||
folder?: string;
|
||||
}): Promise<{ url: string; key: string; size: number }> {
|
||||
assertImageSize(input.buffer.byteLength);
|
||||
|
||||
const allowed = new Set([
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
"image/gif",
|
||||
]);
|
||||
if (!allowed.has(input.contentType)) {
|
||||
throw Object.assign(new Error("Only JPG, PNG, WebP, or GIF allowed"), {
|
||||
statusCode: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const folder = input.folder?.replace(/^\/+|\/+$/g, "") || "uploads";
|
||||
const key = `${folder}/${randomUUID()}.${extensionFor(input.contentType)}`;
|
||||
const bucket = required("S3_BUCKET");
|
||||
const publicBase = (
|
||||
process.env.S3_PUBLIC_BASE_URL ?? required("S3_ENDPOINT")
|
||||
).replace(/\/+$/, "");
|
||||
|
||||
await getClient().send(
|
||||
new PutObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
Body: input.buffer,
|
||||
ContentType: input.contentType,
|
||||
ACL: "public-read",
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
key,
|
||||
size: input.buffer.byteLength,
|
||||
url: `${publicBase}/${key}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export function slugify(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 120);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.post("/login", async (request, reply) => {
|
||||
const parsed = loginSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Invalid credentials payload" });
|
||||
}
|
||||
|
||||
const user = await app.prisma.user.findUnique({
|
||||
where: { email: parsed.data.email.toLowerCase() },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return reply.status(401).send({ error: "Invalid email or password" });
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(parsed.data.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
return reply.status(401).send({ error: "Invalid email or password" });
|
||||
}
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
},
|
||||
};
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { VerificationStatus } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
abstract: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
imageUrl: z.string().url().nullable().optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
categoryIds: z.array(z.string().cuid()).optional(),
|
||||
authorId: z.string().cuid(),
|
||||
verificationStatus: z.nativeEnum(VerificationStatus).optional(),
|
||||
publishedAt: z.coerce.date().nullable().optional(),
|
||||
});
|
||||
|
||||
export const blogRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.blog.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const blog = await app.prisma.blog.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!blog) {
|
||||
return reply.status(404).send({ error: "Blog not found" });
|
||||
}
|
||||
|
||||
return blog;
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.title);
|
||||
const categoryIds = parsed.data.categoryIds ?? [];
|
||||
|
||||
const blog = await app.prisma.blog.create({
|
||||
data: {
|
||||
title: parsed.data.title,
|
||||
slug,
|
||||
abstract: parsed.data.abstract,
|
||||
content: parsed.data.content ?? "",
|
||||
imageUrl: parsed.data.imageUrl ?? null,
|
||||
tags: parsed.data.tags ?? [],
|
||||
authorId: parsed.data.authorId,
|
||||
verificationStatus:
|
||||
parsed.data.verificationStatus ?? VerificationStatus.PENDING,
|
||||
publishedAt: parsed.data.publishedAt ?? null,
|
||||
categories: {
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(blog);
|
||||
});
|
||||
|
||||
app.patch("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const updateSchema = createSchema.partial().omit({ authorId: true });
|
||||
const parsed = updateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const existing = await app.prisma.blog.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return reply.status(404).send({ error: "Blog not found" });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const categoryIds = data.categoryIds;
|
||||
|
||||
const blog = await app.prisma.blog.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.title !== undefined ? { title: data.title } : {}),
|
||||
...(data.title !== undefined || data.slug !== undefined
|
||||
? { slug: slugify(data.slug ?? data.title ?? existing.title) }
|
||||
: {}),
|
||||
...(data.abstract !== undefined ? { abstract: data.abstract } : {}),
|
||||
...(data.content !== undefined ? { content: data.content } : {}),
|
||||
...(data.imageUrl !== undefined ? { imageUrl: data.imageUrl } : {}),
|
||||
...(data.tags !== undefined ? { tags: data.tags } : {}),
|
||||
...(data.verificationStatus !== undefined
|
||||
? { verificationStatus: data.verificationStatus }
|
||||
: {}),
|
||||
...(data.publishedAt !== undefined
|
||||
? { publishedAt: data.publishedAt }
|
||||
: {}),
|
||||
...(categoryIds
|
||||
? {
|
||||
categories: {
|
||||
deleteMany: {},
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return blog;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { VerificationStatus } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const contactSchema = z.object({
|
||||
type: z.enum([
|
||||
"phone",
|
||||
"landline",
|
||||
"email",
|
||||
"instagram",
|
||||
"website",
|
||||
"whatsapp",
|
||||
"other",
|
||||
]),
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
abstract: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
imageUrl: z.string().url().nullable().optional(),
|
||||
galleryUrls: z.array(z.string().url()).optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
country: z.string().min(1),
|
||||
city: z.string().optional(),
|
||||
address: z.string().optional(),
|
||||
contacts: z.array(contactSchema).optional(),
|
||||
categoryIds: z.array(z.string().cuid()).optional(),
|
||||
authorId: z.string().cuid(),
|
||||
verificationStatus: z.nativeEnum(VerificationStatus).optional(),
|
||||
publishedAt: z.coerce.date().nullable().optional(),
|
||||
});
|
||||
|
||||
function assertNoContentImages(content: string | undefined, reply: {
|
||||
status: (code: number) => { send: (body: unknown) => unknown };
|
||||
}) {
|
||||
if (content && /<img\b/i.test(content)) {
|
||||
return reply.status(400).send({
|
||||
error: "Brand main text cannot include images. Use the gallery instead.",
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const brandRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.brand.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const brand = await app.prisma.brand.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!brand) {
|
||||
return reply.status(404).send({ error: "Brand not found" });
|
||||
}
|
||||
|
||||
return brand;
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const contentBlocked = assertNoContentImages(parsed.data.content, reply);
|
||||
if (contentBlocked) return contentBlocked;
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.title);
|
||||
const categoryIds = parsed.data.categoryIds ?? [];
|
||||
const galleryUrls = parsed.data.galleryUrls ?? [];
|
||||
|
||||
const brand = await app.prisma.brand.create({
|
||||
data: {
|
||||
title: parsed.data.title,
|
||||
slug,
|
||||
abstract: parsed.data.abstract,
|
||||
content: parsed.data.content ?? "",
|
||||
imageUrl: parsed.data.imageUrl ?? null,
|
||||
galleryUrls,
|
||||
tags: parsed.data.tags ?? [],
|
||||
country: parsed.data.country,
|
||||
city: parsed.data.city,
|
||||
address: parsed.data.address,
|
||||
contacts: parsed.data.contacts ?? [],
|
||||
authorId: parsed.data.authorId,
|
||||
verificationStatus:
|
||||
parsed.data.verificationStatus ?? VerificationStatus.PENDING,
|
||||
publishedAt: parsed.data.publishedAt ?? null,
|
||||
categories: {
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(brand);
|
||||
});
|
||||
|
||||
app.patch("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const updateSchema = createSchema.partial().omit({ authorId: true });
|
||||
const parsed = updateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const contentBlocked = assertNoContentImages(parsed.data.content, reply);
|
||||
if (contentBlocked) return contentBlocked;
|
||||
|
||||
const existing = await app.prisma.brand.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return reply.status(404).send({ error: "Brand not found" });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const categoryIds = data.categoryIds;
|
||||
const galleryUrls = data.galleryUrls;
|
||||
|
||||
const brand = await app.prisma.brand.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.title !== undefined ? { title: data.title } : {}),
|
||||
...(data.title !== undefined || data.slug !== undefined
|
||||
? { slug: slugify(data.slug ?? data.title ?? existing.title) }
|
||||
: {}),
|
||||
...(data.abstract !== undefined ? { abstract: data.abstract } : {}),
|
||||
...(data.content !== undefined ? { content: data.content } : {}),
|
||||
...(data.imageUrl !== undefined ? { imageUrl: data.imageUrl } : {}),
|
||||
...(galleryUrls !== undefined ? { galleryUrls } : {}),
|
||||
...(data.tags !== undefined ? { tags: data.tags } : {}),
|
||||
...(data.country !== undefined ? { country: data.country } : {}),
|
||||
...(data.city !== undefined ? { city: data.city } : {}),
|
||||
...(data.address !== undefined ? { address: data.address } : {}),
|
||||
...(data.contacts !== undefined ? { contacts: data.contacts } : {}),
|
||||
...(data.verificationStatus !== undefined
|
||||
? { verificationStatus: data.verificationStatus }
|
||||
: {}),
|
||||
...(data.publishedAt !== undefined
|
||||
? { publishedAt: data.publishedAt }
|
||||
: {}),
|
||||
...(categoryIds
|
||||
? {
|
||||
categories: {
|
||||
deleteMany: {},
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return brand;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const createSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
parentId: z.string().cuid().nullable().optional(),
|
||||
});
|
||||
|
||||
export const categoryRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.category.findMany({
|
||||
orderBy: { name: "asc" },
|
||||
include: {
|
||||
children: {
|
||||
orderBy: { name: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.name);
|
||||
if (!slug) {
|
||||
return reply.status(400).send({ error: "Invalid slug" });
|
||||
}
|
||||
|
||||
const category = await app.prisma.category.create({
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
slug,
|
||||
parentId: parsed.data.parentId ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(category);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
|
||||
export const healthRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/health", async () => ({
|
||||
ok: true,
|
||||
service: "novintrades-api",
|
||||
}));
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { VerificationStatus } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
businessOwner: z.string().min(1),
|
||||
abstract: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
imageUrl: z.string().url().nullable().optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
categoryIds: z.array(z.string().cuid()).optional(),
|
||||
authorId: z.string().cuid(),
|
||||
verificationStatus: z.nativeEnum(VerificationStatus).optional(),
|
||||
publishedAt: z.coerce.date().nullable().optional(),
|
||||
});
|
||||
|
||||
export const reportageRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.reportage.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const reportage = await app.prisma.reportage.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!reportage) {
|
||||
return reply.status(404).send({ error: "Reportage not found" });
|
||||
}
|
||||
|
||||
return reportage;
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.title);
|
||||
const categoryIds = parsed.data.categoryIds ?? [];
|
||||
|
||||
const reportage = await app.prisma.reportage.create({
|
||||
data: {
|
||||
title: parsed.data.title,
|
||||
slug,
|
||||
businessOwner: parsed.data.businessOwner,
|
||||
abstract: parsed.data.abstract,
|
||||
content: parsed.data.content ?? "",
|
||||
imageUrl: parsed.data.imageUrl ?? null,
|
||||
tags: parsed.data.tags ?? [],
|
||||
authorId: parsed.data.authorId,
|
||||
verificationStatus:
|
||||
parsed.data.verificationStatus ?? VerificationStatus.PENDING,
|
||||
publishedAt: parsed.data.publishedAt ?? null,
|
||||
categories: {
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(reportage);
|
||||
});
|
||||
|
||||
app.patch("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const updateSchema = createSchema.partial().omit({ authorId: true });
|
||||
const parsed = updateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const existing = await app.prisma.reportage.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return reply.status(404).send({ error: "Reportage not found" });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const categoryIds = data.categoryIds;
|
||||
|
||||
const reportage = await app.prisma.reportage.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.title !== undefined ? { title: data.title } : {}),
|
||||
...(data.title !== undefined || data.slug !== undefined
|
||||
? { slug: slugify(data.slug ?? data.title ?? existing.title) }
|
||||
: {}),
|
||||
...(data.businessOwner !== undefined
|
||||
? { businessOwner: data.businessOwner }
|
||||
: {}),
|
||||
...(data.abstract !== undefined ? { abstract: data.abstract } : {}),
|
||||
...(data.content !== undefined ? { content: data.content } : {}),
|
||||
...(data.imageUrl !== undefined ? { imageUrl: data.imageUrl } : {}),
|
||||
...(data.tags !== undefined ? { tags: data.tags } : {}),
|
||||
...(data.verificationStatus !== undefined
|
||||
? { verificationStatus: data.verificationStatus }
|
||||
: {}),
|
||||
...(data.publishedAt !== undefined
|
||||
? { publishedAt: data.publishedAt }
|
||||
: {}),
|
||||
...(categoryIds
|
||||
? {
|
||||
categories: {
|
||||
deleteMany: {},
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reportage;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import multipart from "@fastify/multipart";
|
||||
import { MAX_IMAGE_BYTES } from "../lib/limits.js";
|
||||
import { uploadImageBuffer } from "../lib/s3.js";
|
||||
|
||||
export const uploadRoutes: FastifyPluginAsync = async (app) => {
|
||||
await app.register(multipart, {
|
||||
limits: {
|
||||
fileSize: MAX_IMAGE_BYTES,
|
||||
files: 1,
|
||||
},
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const query = request.query as { folder?: string };
|
||||
const folder =
|
||||
typeof query.folder === "string" && query.folder.trim()
|
||||
? query.folder.trim()
|
||||
: "uploads";
|
||||
|
||||
const file = await request.file();
|
||||
if (!file) {
|
||||
return reply.status(400).send({ error: "No image file provided" });
|
||||
}
|
||||
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
buffer = await file.toBuffer();
|
||||
} catch {
|
||||
return reply.status(400).send({
|
||||
error: `Image must be ${Math.round(MAX_IMAGE_BYTES / 1024)}KB or smaller`,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const uploaded = await uploadImageBuffer({
|
||||
buffer,
|
||||
contentType: file.mimetype,
|
||||
folder,
|
||||
});
|
||||
return reply.status(201).send(uploaded);
|
||||
} catch (error) {
|
||||
const statusCode =
|
||||
error && typeof error === "object" && "statusCode" in error
|
||||
? Number((error as { statusCode: number }).statusCode)
|
||||
: 500;
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Upload failed";
|
||||
return reply.status(statusCode || 500).send({ error: message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user