Skip to content

Commit

Permalink
finishing api details and db connections with postgres
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielPrediger committed Jan 16, 2024
1 parent d1ecede commit faca2f9
Show file tree
Hide file tree
Showing 12 changed files with 208 additions and 27 deletions.
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PGHOST=''
PGDATABASE=''
PGUSER=''
PGPASSWORD=''
ENDPOINT_ID=''
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
node_modules
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Projeto Node.js - CRUD simples sobre videos

Este projeto foi desenvolvido como parte de um curso simples de Node.js, visando a prática e aprimoramento dos conhecimentos na linguagem.

## Configuração do Banco de Dados

Dentro do projeto, oferecemos a flexibilidade de utilizar um banco de dados local. Para isso, basta realizar a substituição no arquivo `server.js`:

```javascript
const db = new DatabasePostgress();
```

por

```javascript
const db = new DatabaseMemory();
```

## Testando as Rotas

Caso deseje testar as rotas, recomendamos o uso da extensão "REST Client" do VSCode. Você pode interagir com as rotas utilizando o arquivo denominado `routes.http`.

Ao lidar com rotas que possuem identificadores (IDs), lembre-se de substituir no arquivo `routes.http` o `:id` pelo ID gerado ao criar um vídeo.

## Rota de Listagem com Parâmetro de Busca

Destacamos que a rota de listagem de vídeos conta com um parâmetro de busca, utilizando a sintaxe `search=`. Para testar, basta adicionar um título após o sinal de igual.

Exemplo:

```http
GET http://localhost:3000/videos?search=SeuTituloAqui
```

Este projeto oferece uma oportunidade prática de manipulação de rotas em Node.js, permitindo a exploração e aprendizado da linguagem de forma interativa. Sinta-se à vontade para experimentar e personalizar conforme suas necessidades de aprendizado.
12 changes: 12 additions & 0 deletions create-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import sql from "./db.js";

sql`
CREATE TABLE videos (
id TEXT PRIMARY KEY,
title TEXT,
description TEXT,
duration INTEGER
);
`.then(() => {
console.log("Tabala criada!");
});
22 changes: 15 additions & 7 deletions database-memory.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,23 @@ import { randomUUID } from "crypto";
export class DatabaseMemory {
#videos = new Map();

list() {
list(search) {
//entries retorna um array de array que no indice 0 é o id e no indice 1 é os dados
return Array.from(this.#videos.entries()).map((videoArr) => {
//pra isso percorremos o array e retornamos em um novo formato
const id = videoArr[0];
const data = videoArr[1];
return Array.from(this.#videos.entries())
.map((videoArr) => {
//pra isso percorremos o array e retornamos em um novo formato
const id = videoArr[0];
const data = videoArr[1];

return { id, ...data };
});
return { id, ...data };
})
.filter((video) => {
//se tiver uma busca eu retorno o video da busca se nao eu retorno todos
if (search) {
return video.title.includes(search);
}
return true;
});
}

create(video) {
Expand Down
33 changes: 33 additions & 0 deletions database-postgres.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { randomUUID } from "crypto";
import sql from "./db.js";

export class DatabasePostgress {
async list(search) {
let videos;
if (search) {
videos = await sql`select * from videos where title ilike ${
"%" + search + "%"
}`;
} else {
videos = await sql`select * from videos`;
}

return videos;
}

async create(video) {
const videoId = randomUUID();
const { title, description, duration } = video;
await sql`INSERT into videos (id, title, description, duration) VALUES (${videoId}, ${title}, ${description}, ${duration})`;
}

async update(id, video) {
const { title, description, duration } = video;

await sql`UPDATE videos set title = ${title}, description = ${description}, duration = ${duration} WHERE id = ${id}`;
}

async delete(id) {
await sql`DELETE from videos WHERE id = ${id}`;
}
}
25 changes: 25 additions & 0 deletions db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import postgres from "postgres";
import "dotenv/config";

let { PGHOST, PGDATABASE, PGUSER, PGPASSWORD, ENDPOINT_ID } = process.env;

const sql = postgres({
host: PGHOST,
database: PGDATABASE,
username: PGUSER,
password: PGPASSWORD,
port: 5432,
ssl: "require",
connection: {
options: `project=${ENDPOINT_ID}`,
},
});

async function getPgVersion() {
const result = await sql`select version()`;
console.log(result);
}

getPgVersion();

export default sql;
24 changes: 24 additions & 0 deletions node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 30 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
},
"homepage": "https://github.com/GabrielPrediger/nodejs-simple-projetct#readme",
"dependencies": {
"fastify": "^4.25.2"
"fastify": "^4.25.2",
"postgres": "^3.4.3"
},
"devDependencies": {
"dotenv": "^16.3.1"
}
}
15 changes: 9 additions & 6 deletions routes.http
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,31 @@ POST http://localhost:3333/videos
Content-Type: application/json

{
"title":"Video 1",
"description":"Um belo video ",
"title":"Node",
"description":"Um projeto simples em node.js",
"duration": 100
}

###

GET http://localhost:3333/videos?search=Node

###
GET http://localhost:3333/videos


###

PUT http://localhost:3333/videos/id
PUT http://localhost:3333/videos/:id
Content-Type: application/json

{
"title":"Video PUT",
"description":"Um belo video ",
"title":"Node PUT",
"description":"Um belo projeto CRUD em node.js",
"duration": 100
}

###

DELETE http://localhost:3333/videos/
DELETE http://localhost:3333/videos/:id
Content-Type: application/json
24 changes: 13 additions & 11 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import { fastify } from "fastify";
import { DatabaseMemory } from "./database-memory.js";
import { DatabasePostgress } from "./database-postgres.js";

const server = fastify();
const db = new DatabaseMemory();

server.listen({ port: 3333 });
const db = new DatabasePostgress();

server.get("/videos", (request, reply) => {
const videos = db.list();
server.listen({ port: process.env.PORT ?? 3333 });

server.get("/videos", async (request, reply) => {
const search = request.query.search;
const videos = db.list(search);

return videos;
});

server.post("/videos", (request, reply) => {
server.post("/videos", async (request, reply) => {
const { title, description, duration } = request.body;

db.create({
await db.create({
title,
description,
duration,
Expand All @@ -24,11 +26,11 @@ server.post("/videos", (request, reply) => {
return reply.status(201).send();
});

server.put("/videos/:id", (request, reply) => {
server.put("/videos/:id", async (request, reply) => {
const videoId = request.params.id;
const { title, description, duration } = request.body;

db.update(videoId, {
await db.update(videoId, {
title,
description,
duration,
Expand All @@ -37,10 +39,10 @@ server.put("/videos/:id", (request, reply) => {
return reply.status(204).send();
});

server.delete("/videos/:id", (request, reply) => {
server.delete("/videos/:id", async (request, reply) => {
const videoId = request.params.id;

db.delete(videoId);
await db.delete(videoId);

return reply.status(204).send();
});

0 comments on commit faca2f9

Please sign in to comment.