Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelfgx committed Feb 20, 2025
0 parents commit 46b3cfa
Show file tree
Hide file tree
Showing 36 changed files with 604 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MONGODB_URL=mongodb://admin:password@localhost:27017/node?authSource=admin
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* text=auto eol=lf
*.js diff=js
*.ts diff=ts
27 changes: 27 additions & 0 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: build
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Node Setup
uses: actions/setup-node@v4
with:
node-version: latest
check-latest: true

- name: Node Build
run: |
npm run restore
npm run build
- name: Artifact Upload
uses: actions/upload-artifact@v4
with:
name: app
path: dist
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.bat
.vscode
coverage
dist
node_modules
package-lock.json
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
9 changes: 9 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bracketSpacing": true,
"endOfLine": "lf",
"printWidth": 125,
"semi": true,
"singleQuote": false,
"tabWidth": 4,
"trailingComma": "none"
}
39 changes: 39 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# docker compose up --detach --build --force-recreate --remove-orphans

name: node
services:
app:
image: app
container_name: app
depends_on:
- mongo
- mongo-admin
build:
context: .
dockerfile: dockerfile
ports:
- "4000:3000"
environment:
- MONGODB_URL=mongodb://admin:password@mongo:27017/node?authSource=admin
mongo:
image: mongo
container_name: mongo
ports:
- "27017:27017"
volumes:
- ~/volumes/mongo:/data/db
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
mongo-admin:
image: mongo-express
container_name: mongo-admin
depends_on:
- mongo
ports:
- "27018:8081"
environment:
ME_CONFIG_MONGODB_URL: mongodb://admin:password@mongo:27017
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: password
ME_CONFIG_BASICAUTH: false
10 changes: 10 additions & 0 deletions dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM node:alpine
RUN npm install -g pnpm
WORKDIR /app
COPY package.json tsconfig.json ./
RUN pnpm install
COPY ./src ./src
RUN npm run build
EXPOSE 3000
ENV NODE_ENV production
CMD ["node", "dist/main.js"]
31 changes: 31 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import eslint from "@eslint/js";
import eslintTypescript from "typescript-eslint";
import eslintPrettier from "eslint-config-prettier";
import globals from "globals";

export default eslintTypescript.config(
{
ignores: ["*.mjs", "node_modules", "dist"]
},
eslint.configs.recommended,
...eslintTypescript.configs.strict,
...eslintTypescript.configs.stylistic,
eslintPrettier,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest
},
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname
}
}
},
{
rules: {
"@typescript-eslint/no-extraneous-class": "off"
}
}
);
5 changes: 5 additions & 0 deletions jest.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
preset: "ts-jest",
testEnvironment: "node",
setupFilesAfterEnv: ["./test/setup.ts"]
};
5 changes: 5 additions & 0 deletions license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
44 changes: 44 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "node",
"version": "1.0.0",
"license": "MIT",
"scripts": {
"restore": "npm install",
"check": "prettier src test --config .prettierrc --check && eslint",
"fix": "prettier src test --config .prettierrc --write && eslint --fix",
"start": "nodemon --inspect=3000 -e ts --exec node -r ts-node/register src/main.ts",
"test": "jest --no-cache --coverage",
"build": "tsc"
},
"dependencies": {
"cors": "2.8.5",
"dotenv": "16.4.7",
"express": "5.0.1",
"helmet": "8.0.0",
"joi": "17.13.3",
"mongodb": "6.13.0",
"mongoose": "8.10.1"
},
"devDependencies": {
"@eslint/js": "9.20.0",
"@testcontainers/mongodb": "10.18.0",
"@types/cors": "2.8.17",
"@types/express": "5.0.0",
"@types/jest": "29.5.14",
"@types/node": "22.13.4",
"@types/supertest": "6.0.2",
"eslint": "9.20.1",
"eslint-config-prettier": "10.0.1",
"eslint-plugin-prettier": "5.2.3",
"globals": "16.0.0",
"jest": "29.7.0",
"nodemon": "3.1.9",
"prettier": "3.5.1",
"supertest": "7.0.0",
"testcontainers": "10.18.0",
"ts-jest": "29.2.5",
"ts-node": "10.9.2",
"typescript": "5.7.3",
"typescript-eslint": "8.24.1"
}
}
46 changes: 46 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Node

API using Node, Express, MongoDB, ESLint, Prettier, Folder-by-Feature Structure.

## TECHNOLOGIES

* [Node](https://nodejs.org)
* [Express](https://expressjs.com)
* [MongoDB](https://www.mongodb.com)
* [ESLint](https://eslint.org)
* [Prettier](https://prettier.io)

## RUN

<details>
<summary>Visual Studio Code</summary>

#### Prerequisites

* [Docker](https://www.docker.com/get-started)
* [Node](https://nodejs.org)
* [Visual Studio Code](https://code.visualstudio.com)

#### Steps

1. Run the command **docker compose up --detach --build --force-recreate --remove-orphans** in the **Terminal**.
2. Run the command **npm run restore** in the **Terminal**.
3. Run the command **npm run start** in the **Terminal**.
4. Press **F5** (only for debugging).
5. Open **<http://localhost:3000>** in the **Web Browser**.

</details>

<details>
<summary>Docker</summary>

#### Prerequisites

* [Docker](https://www.docker.com/get-started)

#### Steps

1. Run the command **docker compose up --detach --build --force-recreate --remove-orphans** in the **Terminal**.
2. Open **<http://localhost:4000>** in the **Web Browser**.

</details>
32 changes: 32 additions & 0 deletions src/customer/customer.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Request, Response } from "express";
import CustomerService from "./customer.service";

export default class CustomerController {
constructor(private readonly customerService: CustomerService) {}

list = async (_request: Request, response: Response) => {
const result = await this.customerService.list();
response.status(result.length ? 200 : 404).json(result.length ? result : undefined);
};

get = async (request: Request, response: Response) => {
const result = await this.customerService.get(request.params["id"] ?? "");
response.status(result ? 200 : 404).json(result || undefined);
};

add = async (request: Request, response: Response) => {
const result = await this.customerService.add(request.body);
response.status(201).json(result);
};

update = async (request: Request, response: Response) => {
request.body.id = request.params["id"];
await this.customerService.update(request.body);
response.status(200).send();
};

remove = async (request: Request, response: Response) => {
await this.customerService.remove(request.params["id"] ?? "");
response.status(204).send();
};
}
4 changes: 4 additions & 0 deletions src/customer/customer.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default interface Customer {
readonly id: string;
readonly name: string;
}
5 changes: 5 additions & 0 deletions src/customer/customer.mapping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Customer from "./customer.entity";
import CustomerDto from "./dto/customer.dto";

export const map = (customer: Customer | undefined | null): CustomerDto | null =>
!customer ? null : { id: customer.id, name: customer.name };
24 changes: 24 additions & 0 deletions src/customer/customer.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import customers from "./customer.schema";
import Customer from "./customer.entity";

export default class CustomerRepository {
list = async (): Promise<Customer[]> => {
return await customers.find();
};

get = async (id: string): Promise<Customer | null> => {
return await customers.findById(id);
};

add = async (customer: Customer): Promise<string> => {
return (await customers.create(customer)).id;
};

update = async (customer: Customer): Promise<void> => {
await customers.findByIdAndUpdate(customer.id, customer);
};

remove = async (id: string): Promise<void> => {
await customers.findByIdAndDelete(id);
};
}
17 changes: 17 additions & 0 deletions src/customer/customer.router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import express from "express";
import validate from "../shared/validate";
import CustomerController from "./customer.controller";
import CustomerService from "./customer.service";
import CustomerRepository from "./customer.repository";
import { addValidator, updateValidator } from "./customer.validation";

const router = express.Router();
const customerController = new CustomerController(new CustomerService(new CustomerRepository()));

router.get("/", customerController.list);
router.get("/:id", customerController.get);
router.post("/", validate(addValidator), customerController.add);
router.put("/:id", validate(updateValidator), customerController.update);
router.delete("/:id", customerController.remove);

export default router;
12 changes: 12 additions & 0 deletions src/customer/customer.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as mongoose from "mongoose";
import Customer from "./customer.entity";

export default mongoose.model(
"customers",
new mongoose.Schema<Customer>({
name: {
type: String,
required: true
}
})
);
29 changes: 29 additions & 0 deletions src/customer/customer.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { map } from "./customer.mapping";
import CustomerRepository from "./customer.repository";
import CustomerDto from "./dto/customer.dto";
import AddCustomerDto from "./dto/add.customer.dto";
import UpdateCustomerDto from "./dto/update.customer.dto";

export default class CustomerService {
constructor(private readonly customerRepository: CustomerRepository) {}

list = async (): Promise<CustomerDto[]> => {
return (await this.customerRepository.list()).map(map) as CustomerDto[];
};

get = async (id: string): Promise<CustomerDto | null> => {
return map(await this.customerRepository.get(id));
};

add = async (dto: AddCustomerDto): Promise<string> => {
return await this.customerRepository.add({ ...dto, id: "" });
};

update = async (dto: UpdateCustomerDto): Promise<void> => {
await this.customerRepository.update({ ...dto });
};

remove = async (id: string): Promise<void> => {
await this.customerRepository.remove(id);
};
}
12 changes: 12 additions & 0 deletions src/customer/customer.validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import Joi from "joi";

const name = Joi.string().min(2).max(250).required();

export const addValidator = Joi.object({
name: name
});

export const updateValidator = Joi.object({
id: Joi.string().required(),
name: name
});
3 changes: 3 additions & 0 deletions src/customer/dto/add.customer.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default interface AddCustomerDto {
readonly name: string;
}
Loading

0 comments on commit 46b3cfa

Please sign in to comment.