Skip to content

Commit

Permalink
setup prisma: prisma repositories, prisma mappers
Browse files Browse the repository at this point in the history
  • Loading branch information
Bruno Fernandes committed Jun 18, 2024
1 parent 000fe93 commit 3348235
Show file tree
Hide file tree
Showing 41 changed files with 1,281 additions and 22 deletions.
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ version: "3.8"

services:
postgres:
container_name: nest-clean-pg
container_name: fast-feet-pg
image: bitnami/postgresql
ports:
- 5432:5432
environment:
- POSTGRESQL_USERNAME=postgres
- POSTGRESQL_PASSWORD=docker
- POSTGRESQL_DATABASE=nest-clean
- POSTGRESQL_DATABASE=fast-feet
- PG_DATA=/data/postgres
volumes:
- ./data/pg:/data/postgres
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"private": true,
"license": "UNLICENSED",
"scripts": {
"db": "prisma studio",
"build": "nest build",
"start": "nest start",
"dev": "nest start --watch",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
-- CreateEnum
CREATE TYPE "UserRoles" AS ENUM ('recipient', 'adm', 'courier');

-- CreateEnum
CREATE TYPE "UpdateObjectTypes" AS ENUM ('recipient', 'adm', 'courier', 'order');

-- CreateTable
CREATE TABLE "orders" (
"id" TEXT NOT NULL,
"recipient_d" TEXT NOT NULL,
"courier_id" TEXT,
"address" JSONB NOT NULL,
"delivered" TIMESTAMP(3),
"delivered_photo" JSONB,
"awaiting_pickup" TIMESTAMP(3),
"collected" TIMESTAMP(3),
"returned" TIMESTAMP(3),
"return_cause" TEXT,
"created_at" TIMESTAMP(3) NOT NULL,
"updated_at" TIMESTAMP(3),

CONSTRAINT "orders_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"cpf" TEXT NOT NULL,
"password" TEXT NOT NULL,
"role" "UserRoles" NOT NULL,
"coordinates" JSONB,
"created_at" TIMESTAMP(3) NOT NULL,
"updated_at" TIMESTAMP(3),

CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "updates" (
"id" TEXT NOT NULL,
"object_id" TEXT NOT NULL,
"updated_by" TEXT NOT NULL,
"date" TIMESTAMP(3) NOT NULL,
"changes" JSONB NOT NULL,
"object_type" "UpdateObjectTypes" NOT NULL,

CONSTRAINT "updates_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "users_cpf_key" ON "users"("cpf");

-- AddForeignKey
ALTER TABLE "orders" ADD CONSTRAINT "orders_recipient_d_fkey" FOREIGN KEY ("recipient_d") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "orders" ADD CONSTRAINT "orders_courier_id_fkey" FOREIGN KEY ("courier_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "updates" ADD CONSTRAINT "updates_updated_by_fkey" FOREIGN KEY ("updated_by") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
12 changes: 12 additions & 0 deletions prisma/migrations/20240618212407_create_attachments/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- CreateTable
CREATE TABLE "PrismaAttachments" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"url" TEXT NOT NULL,
"orderId" TEXT,

CONSTRAINT "PrismaAttachments_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "PrismaAttachments" ADD CONSTRAINT "PrismaAttachments_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "orders"("id") ON DELETE SET NULL ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- AlterTable
ALTER TABLE "orders" ALTER COLUMN "address" SET DATA TYPE TEXT,
ALTER COLUMN "delivered_photo" SET DATA TYPE TEXT;

-- AlterTable
ALTER TABLE "updates" ALTER COLUMN "changes" SET DATA TYPE TEXT;

-- AlterTable
ALTER TABLE "users" ALTER COLUMN "coordinates" SET DATA TYPE TEXT;
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
87 changes: 87 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model PrismaOrder {
id String @id @default(uuid())
recipientId String @map("recipient_d")
courierId String? @map("courier_id")
address String
delivered DateTime?
deliveredPhoto String? @map("delivered_photo")
awaitingPickup DateTime? @map("awaiting_pickup")
collected DateTime?
returned DateTime?
returnCause String? @map("return_cause")
createdAt DateTime @map("created_at")
updatedAt DateTime? @map("updated_at")
recipient PrismaUser @relation("recipient", fields: [recipientId], references: [id])
courier PrismaUser? @relation("courier", fields: [courierId], references: [id])
attachments PrismaAttachments[]
@@map("orders")
}

enum UserRoles {
recipient
adm
courier
}

model PrismaUser {
id String @id @default(uuid())
name String
cpf String @unique
password String
role UserRoles
coordinates String?
createdAt DateTime @map("created_at")
updatedAt DateTime? @map("updated_at")
recipient PrismaOrder[] @relation("recipient")
courier PrismaOrder[] @relation("courier")
updates PrismaUpdates[]
@@map("users")
}

enum UpdateObjectTypes {
recipient
adm
courier
order
}

model PrismaUpdates {
id String @id @default(uuid())
objectId String @map("object_id")
updatedBy String @map("updated_by")
date DateTime
changes String
objectType UpdateObjectTypes @map("object_type")
user PrismaUser @relation(fields: [updatedBy], references: [id])
@@map("updates")
}

model PrismaAttachments {
id String @id @default(uuid())
title String
url String
orderId String?
order PrismaOrder? @relation(fields: [orderId], references: [id])
}
7 changes: 7 additions & 0 deletions src/core/errors/errors/entity-type-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { UseCaseError } from '@/core/errors/use-case-errors'

export class EntityTypeError extends Error implements UseCaseError {
constructor(message: string) {
super(message)
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { UpdateAdm } from '../../../enterprise/entities/update-adm'

@Injectable()
export abstract class AdmUpdatesRepository {
abstract create(update: UpdateAdm): Promise<void>
abstract update(update: UpdateAdm): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { Adm } from '../../../enterprise/entities/adm'

@Injectable()
export abstract class AdmsRepository {
abstract create(adm: Adm): Promise<void>
abstract update(adm: Adm): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { Attachment } from '../../enterprise/entities/attachment'

@Injectable()
export abstract class AttachmentsRepository {
abstract create(update: Attachment): Promise<void>
abstract findById(id: string): Promise<Attachment | null>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { Courier } from '../../../enterprise/entities/courier'

@Injectable()
export abstract class CouriersRepository {
abstract create(courier: Courier): Promise<void>
abstract update(courier: Courier): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { UpdateCourier } from '../../../enterprise/entities/update-courier'

@Injectable()
export abstract class CourierUpdatesRepository {
abstract create(update: UpdateCourier): Promise<void>
abstract update(update: UpdateCourier): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { OrderAttachment } from '../../../enterprise/entities/order-attachment'

@Injectable()
export abstract class OrderAttachmentsRepository {
abstract create(update: OrderAttachment): Promise<void>
abstract findByOrderId(orderId: string): Promise<OrderAttachment | null>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { UpdateOrder } from '../../../enterprise/entities/update-order'

@Injectable()
export abstract class OrderUpdatesRepository {
abstract create(update: UpdateOrder): Promise<void>
abstract update(update: UpdateOrder): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { Injectable } from '@nestjs/common'
import { Order } from '../../../enterprise/entities/order'
import { Coordinates } from '../../../enterprise/entities/value-objects/coordinates'

@Injectable()
export abstract class OrdersRepository {
abstract create(order: Order): Promise<void>
abstract update(order: Order): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { UpdateRecipient } from '../../../enterprise/entities/update-recipient'

@Injectable()
export abstract class RecipientUpdatesRepository {
abstract create(update: UpdateRecipient): Promise<void>
abstract update(update: UpdateRecipient): Promise<void>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common'
import { Recipient } from '../../../enterprise/entities/recipient'

@Injectable()
export abstract class RecipientsRepository {
abstract create(recipient: Recipient): Promise<void>
abstract update(recipient: Recipient): Promise<void>
Expand Down
8 changes: 8 additions & 0 deletions src/infra/database/database.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common'
import { PrismaService } from './prisma/prisma.service'
import { repositories } from './prisma/prisma.exports'

@Module({
providers: [PrismaService, ...repositories],
})
export class DatabaseModule {}
58 changes: 58 additions & 0 deletions src/infra/database/prisma/mappers/prisma-adm-mapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import UniqueEntityId from '@/core/entities/unique-entity-id'
import { EntityTypeError } from '@/core/errors/errors/entity-type-error'
import { Adm } from '@/domain/core/deliveries-and-orders/enterprise/entities/adm'
import {
Coordinates,
CoordinatesProps,
} from '@/domain/core/deliveries-and-orders/enterprise/entities/value-objects/coordinates'
import { Cpf } from '@/domain/core/deliveries-and-orders/enterprise/entities/value-objects/cpf'
import { PrismaUser } from '@prisma/client'

export class PrismaAdmMapper {
static toDomain(prismaAdm: PrismaUser): Adm {
if (prismaAdm.role !== 'adm')
throw new EntityTypeError(
`Adm.role must be equal "adm", but "${prismaAdm.role}" was passed`,
)

const coordinates = prismaAdm.coordinates
? new Coordinates(
JSON.parse(prismaAdm.coordinates as string) as CoordinatesProps,
)
: null

const update = Adm.create(
{
cpf: new Cpf(prismaAdm.cpf),
name: prismaAdm.name,
password: prismaAdm.password,
role: prismaAdm.role,
coordinates,
createdAt: prismaAdm.createdAt,
updatedAt: prismaAdm.updatedAt,
},
new UniqueEntityId(prismaAdm.id),
)

return update
}

static domainToPrisma(adm: Adm): PrismaUser {
const coordinates = adm.coordinates?.raw
? JSON.stringify(adm.coordinates.raw)
: null

const prismaAdm: PrismaUser = {
id: adm.id.value,
cpf: adm.cpf.raw,
name: adm.name,
password: adm.password,
role: adm.role,
coordinates,
createdAt: adm.createdAt,
updatedAt: adm.updatedAt,
}

return prismaAdm
}
}
33 changes: 33 additions & 0 deletions src/infra/database/prisma/mappers/prisma-attachment-mapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import UniqueEntityId from '@/core/entities/unique-entity-id'
import { Attachment } from '@/domain/core/deliveries-and-orders/enterprise/entities/attachment'
import { PrismaAttachments } from '@prisma/client'

export class PrismaAttachmentMapper {
static toDomain(prismaAttachment: PrismaAttachments): Attachment {
const orderId = prismaAttachment.orderId
? new UniqueEntityId(prismaAttachment.orderId)
: null

const update = Attachment.create(
{
title: prismaAttachment.title,
url: prismaAttachment.url,
orderId,
},
new UniqueEntityId(prismaAttachment.id),
)

return update
}

static domainToPrisma(attachment: Attachment): PrismaAttachments {
const prismaAttachment: PrismaAttachments = {
id: attachment.id.value,
orderId: attachment.id.value,
title: attachment.title,
url: attachment.url,
}

return prismaAttachment
}
}
Loading

0 comments on commit 3348235

Please sign in to comment.