Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion infra/controller.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { InternalServerError, MethodNotAllowedError } from "infra/errors";
import {
InternalServerError,
MethodNotAllowedError,
ValidationError,
NotFoundError,
} from "infra/errors";

function onNoMatchHandler(request, response) {
const publicErrorObject = new MethodNotAllowedError();
response.status(publicErrorObject.statusCode).json(publicErrorObject);
}

function onErrorHandler(error, request, response) {
if (error instanceof ValidationError || error instanceof NotFoundError) {
return response.status(error.statusCode).json(error);
}

const publicErrorObject = new InternalServerError({
statusCode: error.statusCode,
cause: error,
Expand Down
41 changes: 41 additions & 0 deletions infra/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,47 @@ export class ServiceError extends Error {
}
}

export class ValidationError extends Error {
constructor({ cause, message, action }) {
super(message || "Um erro de validação ocorreu.", {
cause,
});
this.name = "ValidationError";
this.action = action || "Ajuste os dados enviados e tente novamente.";
this.statusCode = 400;
}

toJSON() {
return {
name: this.name,
message: this.message,
action: this.action,
status_code: this.statusCode,
};
}
}

export class NotFoundError extends Error {
constructor({ cause, message, action }) {
super(message || "Não foi possível encontrar este recurso no sistema.", {
cause,
});
this.name = "NotFoundError";
this.action =
action || "Verifique se os parâmetros enviados na consulta estão certos.";
this.statusCode = 404;
}

toJSON() {
return {
name: this.name,
message: this.message,
action: this.action,
status_code: this.statusCode,
};
}
}

export class MethodNotAllowedError extends Error {
constructor() {
super("Método não permitido para este endpoint.");
Expand Down
8 changes: 0 additions & 8 deletions infra/migrations/1755523095078_test-migration.js

This file was deleted.

44 changes: 44 additions & 0 deletions infra/migrations/1755978902703_users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
exports.up = (pgm) => {
pgm.createTable("users", {
id: {
type: "uuid",
primaryKey: true,
default: pgm.func("gen_random_uuid()"),
},

// For reference, GitHub limits usernames to 39 characters.
username: {
type: "varchar(30)",
notNull: true,
unique: true,
},

// Why 254 in length? https://stackoverflow.com/a/1199238
email: {
type: "varchar(254)",
notNull: true,
unique: true,
},

// Why 60 in length? https://www.npmjs.com/package/bcrypt#hash-info
password: {
type: "varchar(60)",
notNull: true,
},

// Why timestamp with timezone? https://justatheory.com/2012/04/postgres-use-timestamptz/
created_at: {
type: "timestamptz",
notNull: true,
default: pgm.func("timezone('utc', now())"),
},

updated_at: {
type: "timestamptz",
notNull: true,
default: pgm.func("timezone('utc', now())"),
},
});
};

exports.down = false;
2 changes: 1 addition & 1 deletion models/migrator.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const defaultMigrationOptions = {
dryRun: true,
dir: resolve("infra", "migrations"),
direction: "up",
verbose: true,
log: () => {},
migrationsTable: "pgmigrations",
};

Expand Down
109 changes: 109 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import database from "infra/database.js";
import { ValidationError, NotFoundError } from "infra/errors.js";

async function findOneByUsername(username) {
const userFound = await runSelectQuery(username);

return userFound;

async function runSelectQuery(username) {
const results = await database.query({
text: `
SELECT
*
FROM
users
WHERE
LOWER(username) = LOWER($1)
LIMIT
1
;`,
values: [username],
});

if (results.rowCount === 0) {
throw new NotFoundError({
message: "O username informado não foi encontrado no sistema.",
action: "Verifique se o username está digitado corretamente.",
});
}

return results.rows[0];
}
}

async function create(userInputValues) {
await validateUniqueEmail(userInputValues.email);
await validateUniqueUsername(userInputValues.username);

const newUser = await runInsertQuery(userInputValues);
return newUser;

async function validateUniqueEmail(email) {
const results = await database.query({
text: `
SELECT
email
FROM
users
WHERE
LOWER(email) = LOWER($1)
;`,
values: [email],
});

if (results.rowCount > 0) {
throw new ValidationError({
message: "O email informado já está sendo utilizado.",
action: "Utilize outro email para realizar o cadastro.",
});
}
}

async function validateUniqueUsername(username) {
const results = await database.query({
text: `
SELECT
username
FROM
users
WHERE
LOWER(username) = LOWER($1)
;`,
values: [username],
});

if (results.rowCount > 0) {
throw new ValidationError({
message: "O username informado já está sendo utilizado.",
action: "Utilize outro username para realizar o cadastro.",
});
}
}

async function runInsertQuery(userInputValues) {
const results = await database.query({
text: `
INSERT INTO
users (username, email, password)
VALUES
($1, $2, $3)
RETURNING
*
;`,
values: [
userInputValues.username,
userInputValues.email,
userInputValues.password,
],
});
return results.rows[0];
}
}

const user = {
create,
findOneByUsername,
};

export default user;
15 changes: 14 additions & 1 deletion package-lock.json

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

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
"pg": "8.11.3",
"react": "18.2.0",
"react-dom": "18.2.0",
"swr": "2.2.5"
"swr": "2.2.5",
"uuid": "11.1.0"
},
"devDependencies": {
"@commitlint/cli": "19.3.0",
Expand Down
15 changes: 15 additions & 0 deletions pages/api/v1/users/[username]/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createRouter } from "next-connect";
import controller from "infra/controller.js";
import user from "models/user.js";

const router = createRouter();

router.get(getHandler);

export default router.handler(controller.errorHandlers);

async function getHandler(request, response) {
const username = request.query.username;
const userFound = await user.findOneByUsername(username);
return response.status(200).json(userFound);
}
15 changes: 15 additions & 0 deletions pages/api/v1/users/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createRouter } from "next-connect";
import controller from "infra/controller.js";
import user from "models/user.js";

const router = createRouter();

router.post(postHandler);

export default router.handler(controller.errorHandlers);

async function postHandler(request, response) {
const userInputValues = request.body;
const newUser = await user.create(userInputValues);
return response.status(201).json(newUser);
}
Loading