0% found this document useful (0 votes)
6 views5 pages

Node.js CRUD with PostgreSQL & TypeScript

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Node.js CRUD with PostgreSQL & TypeScript

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ChatGPT

Claro, vou te guiar através da criação de um CRUD básico em [Link] com PostgreSQL
e TypeScript, seguindo o padrão de arquitetura MVC (Model-View-Controller) com
serviços adicionados.

Vamos começar criando a estrutura de pastas e arquivos:

1. Criar uma pasta para o projeto e navegar até ela:

bash
Copiar código
mkdir nodejs-crud
cd nodejs-crud

2. Iniciar um projeto [Link] e configurar TypeScript:

bash
Copiar código
npm init -y
npm install typescript ts-node @types/node
npx tsc --init

3. Instalar as dependências necessárias:

bash
Copiar código
npm install express pg pg-promise body-parser

Agora, vamos criar a estrutura básica do nosso aplicativo:

plaintext
Copiar código
nodejs-crud/

├── src/
│ ├── controllers/
│ │ └── [Link]
│ │
│ ├── models/
│ │ └── [Link]
│ │
│ ├── services/
│ │ └── [Link]
│ │
│ ├── routes/
│ │ └── [Link]
│ │
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── [Link]

├── .gitignore
└── [Link]
Agora, vamos preencher cada um desses arquivos com o código apropriado:

1. [Link]:

typescript
Copiar código
export const DB_CONFIG = {
host: 'localhost',
port: 5432,
database: 'crud_db',
user: 'postgres',
password: 'your_password_here',
};

2. [Link]:

typescript
Copiar código
import { DB_CONFIG } from './config';
import pgPromise from 'pg-promise';

const pgp = pgPromise();


const db = pgp(DB_CONFIG);

export default db;

3. [Link]:

typescript
Copiar código
export interface Item {
id?: number;
name: string;
description: string;
}

4. [Link]:

typescript
Copiar código
import db from '../db';
import { Item } from '../types';

class ItemModel {
async getAllItems(): Promise<Item[]> {
return [Link]('SELECT * FROM items');
}

async getItemById(id: number): Promise<Item | null> {


return [Link]('SELECT * FROM items WHERE id = $1', id);
}

async createItem(item: Item): Promise<Item> {


return [Link]('INSERT INTO items(name, description) VALUES($1, $2)
RETURNING *', [
[Link],
[Link],
]);
}

async updateItem(id: number, item: Item): Promise<Item | null> {


return [Link](
'UPDATE items SET name = $1, description = $2 WHERE id = $3
RETURNING *',
[[Link], [Link], id]
);
}

async deleteItem(id: number): Promise<void> {


await [Link]('DELETE FROM items WHERE id = $1', id);
}
}

export default new ItemModel();

5. [Link]:

typescript
Copiar código
import itemModel from '../models/itemModel';
import { Item } from '../types';

class ItemService {
async getAllItems(): Promise<Item[]> {
return [Link]();
}

async getItemById(id: number): Promise<Item | null> {


return [Link](id);
}

async createItem(item: Item): Promise<Item> {


return [Link](item);
}

async updateItem(id: number, item: Item): Promise<Item | null> {


return [Link](id, item);
}

async deleteItem(id: number): Promise<void> {


return [Link](id);
}
}

export default new ItemService();

6. [Link]:

typescript
Copiar código
import { Request, Response } from 'express';
import itemService from '../services/itemService';
import { Item } from '../types';

class ItemController {
async getAllItems(req: Request, res: Response): Promise<void> {
const items = await [Link]();
[Link](items);
}

async getItemById(req: Request, res: Response): Promise<void> {


const id = parseInt([Link]);
const item = await [Link](id);
if (item) {
[Link](item);
} else {
[Link](404).json({ message: 'Item not found' });
}
}

async createItem(req: Request, res: Response): Promise<void> {


const newItem: Item = [Link];
const createdItem = await [Link](newItem);
[Link](201).json(createdItem);
}

async updateItem(req: Request, res: Response): Promise<void> {


const id = parseInt([Link]);
const updatedItem: Item = [Link];
const item = await [Link](id, updatedItem);
if (item) {
[Link](item);
} else {
[Link](404).json({ message: 'Item not found' });
}
}

async deleteItem(req: Request, res: Response): Promise<void> {


const id = parseInt([Link]);
await [Link](id);
[Link](204);
}
}

export default new ItemController();

7. [Link]:

typescript
Copiar código
import express from 'express';
import itemController from '../controllers/itemController';

const router = [Link]();

[Link]('/', [Link]);
[Link]('/:id', [Link]);
[Link]('/', [Link]);
[Link]('/:id', [Link]);
[Link]('/:id', [Link]);

export default router;

8. [Link]:

typescript
Copiar código
import express, { Application, Request, Response } from 'express';
import bodyParser from 'body-parser';
import itemRoutes from './routes/itemRoutes';

const app: Application = express();


const PORT = 3000;

// Middleware
[Link]([Link]());

// Routes
[Link]('/items', itemRoutes);

// Error handler
[Link]((err: any, req: Request, res: Response, next: Function) => {
[Link]([Link]);
[Link](500).send('Something broke!');
});

[Link](PORT, () => {
[Link](`Server is listening on port ${PORT}`);

You might also like