hngprojects / hng_boilerplate_nestjs

Description
Apache License 2.0
181 stars 105 forks source link

[FEAT]Databsae setup - Migration, Seeding and Model #268

Closed posh1001 closed 1 month ago

posh1001 commented 1 month ago

Description

Establish a secure and flexible database schema using Object-Relational Mapping (ORM) with PostgreSQL as the primary database backend, while ensuring the architecture supports easy migration to other database types. The focus will be on creating tables for users, profiles, and organizations, following best practices for Nest.js projects.

Database Configuration:

ORM Integration:

Migrations Setup:

Setup validation:

Install Required Packages

Make sure you have class-validator and class-transformer installed in your NestJS project. If not, you can install them using npm or yarn:

Create an Entity Class

Create your entity class where you want to apply validation. For example, let's create a simple User entity:

Apply Validation Pipes

In NestJS, you use pipes to handle validation. There's a built-in ValidationPipe that integrates with class-validator to automatically validate incoming request payloads.

Validate DTOs (Data Transfer Objects)

It's a good practice in NestJS to use DTOs for data validation and transformation between clients and your application. Here’s an example of a DTO with validation:

Handle Validation Errors

When validation fails, NestJS automatically throws a BadRequestException with details of the validation errors. You can customize the error handling by catching exceptions globally using custom filters or handling them within specific controllers.

Table Seeding

Setup Endpoint

[GET] api/v1/users/user_one_id

Outcome

{ name: 'John Doe', id: 'some-user-id', email: 'johndoe@example.com', profile: { first_name: 'John', last_ame: 'Doe', phone: '1234567890', avatar_url: 'http://example.com/avatar.jpg', }, organisations: [ { org_id: 'some-org-id-1', name: 'Some Org', description: 'Some Org Description', }, { org_id: 'some-other-org-id-2', name: 'Some Other Org', description: 'Some Other Org Description', }, ], products: [ { product_id: 'some-product-id', name: 'Some Product', description: 'Some Product Description', }, {
product_id: 'some-other-product-id', name: 'Some Other Product', description: 'Some Other Product Description', }, ], }

markessien commented 1 month ago

No db ticket will be accepted