### Example: Basic Express Route Setup Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md A simple example demonstrating how to set up a basic route in an Express.js application using TypeScript. ```typescript import express, { Request, Response } from 'express'; const app = express(); const port = 3000; app.get('/', (req: Request, res: Response) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); }); ``` -------------------------------- ### Example: Basic GraphQL Query Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md Illustrates a basic GraphQL query structure for fetching data. ```graphql query GetUserData($userId: ID!) { user(id: $userId) { id name email } } ``` -------------------------------- ### Listar Enquetes Source: https://github.com/rmanguinho/clean-ts-api/blob/master/requirements/load-surveys.md Esta documentação descreve a rota GET /api/surveys para listar todas as enquetes. A rota valida se a requisição é feita por um usuário autenticado. Retorna 204 se não houver enquetes, 200 com os dados das enquetes em caso de sucesso, 404 se a API não for encontrada, 403 se o usuário não for autorizado, e 500 para erros internos do servidor. ```APIDOC GET /api/surveys Descrição: Lista todas as enquetes disponíveis. Autenticação: Requer autenticação de usuário. Respostas: 204 No Content: Caso não haja nenhuma enquete registrada. 200 OK: Retorna um array de enquetes. Exemplo: [ { "id": "uuid-da-enquete", "title": "Qual sua linguagem de programação favorita?", "questions": [ "JavaScript", "Python", "Java" ] } ] 404 Not Found: Caso a rota da API não seja encontrada. 403 Forbidden: Caso a requisição não seja feita por um usuário autorizado. 500 Internal Server Error: Caso ocorra um erro ao tentar listar as enquetes. ``` -------------------------------- ### Get Survey Results API Source: https://github.com/rmanguinho/clean-ts-api/blob/master/requirements/load-survey-result.md Retrieves the results of a specific survey. Requires user authentication and handles various error conditions. ```APIDOC GET /api/surveys/{survey_id}/results Description: Retrieves the results of a specific survey. Authentication: Requires a valid user authentication. Success Response: - Status Code: 200 - Body: Survey result data Error Responses: - Status Code: 404 Description: Survey not found. - Status Code: 403 Description: Forbidden - User not authorized. - Status Code: 500 Description: Internal Server Error - Failed to list survey results. ``` -------------------------------- ### User Signup API Endpoint Source: https://github.com/rmanguinho/clean-ts-api/blob/master/requirements/signup.md Handles user registration via a POST request. It validates input data, encrypts passwords, generates access tokens, and updates user records. Includes detailed error handling for various failure conditions. ```APIDOC POST /api/signup Request Body: name: string (required) email: string (required, valid email format) password: string (required) passwordConfirmation: string (required, must match password) Success Response (200 OK): token: string (access token) name: string (user's name) Error Responses: 404 Not Found: If the API endpoint does not exist. 400 Bad Request: - If 'name', 'email', 'password', or 'passwordConfirmation' are missing. - If 'password' and 'passwordConfirmation' do not match. - If 'email' is not a valid email format. 403 Forbidden: If the provided email is already in use. 500 Internal Server Error: - If there's an error during password encryption. - If there's an error creating the user account. - If there's an error generating the access token. - If there's an error updating the user with the access token. ``` -------------------------------- ### API Documentation - Core Features Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md Provides an overview of the API's core features, including RESTful API with Express, GraphQL with Apollo Server, error logging, security measures, CORS, middleware, and access control levels. ```apidoc API Documentation: Features: - API Rest with Express - GraphQL with Apollo Server - Error Logging - Security (Hashing, Encryption, Encoding) - CORS - Middlewares - Access Levels (Admin, User, Anonymous) - Deploy on Heroku - Serve Static Files ``` -------------------------------- ### Login API Endpoint Source: https://github.com/rmanguinho/clean-ts-api/blob/master/requirements/login.md Handles user login requests via POST method. Validates email and password, generates an access token, and updates user data. Returns the token and username on success, or appropriate error codes for various failure scenarios. ```APIDOC POST /api/login **Success Case (200 OK):** 1. Receives POST request with email and password. 2. Validates mandatory fields (email, password). 3. Validates email format. 4. Finds user by email and password. 5. Generates an access token using the user ID. 6. Updates user data with the generated access token. 7. Returns 200 with the access token and username. **Error Cases:** - **404 Not Found:** If the API route does not exist. - **400 Bad Request:** If email or password are not provided. - **400 Bad Request:** If the email field is not a valid email format. - **401 Unauthorized:** If no user is found with the provided credentials. - **500 Internal Server Error:** If an error occurs during token generation. - **500 Internal Server Error:** If an error occurs during user data update. ``` -------------------------------- ### Testing Features Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md Describes the testing strategies and features implemented, including unit tests, integration tests (REST & GraphQL), test coverage, test doubles, mocks, stubs, spies, and fakes. ```apidoc Testing Features: - Unit Tests - Integration Tests (API Rest & GraphQL) - Test Coverage - Test Doubles - Mocks - Stubs - Spies - Fakes ``` -------------------------------- ### TypeScript Features Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md Highlights the advanced TypeScript features employed, including OOP, interfaces, type aliases, namespaces, utility types, path modularization, configuration, build, and deployment. ```apidoc TypeScript Features: - Advanced OOP - Interface - TypeAlias - Namespace - Utility Types - Path Modularization - Configurations - Build - Deploy - Use of Breakpoints ``` -------------------------------- ### GraphQL Features Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md Details the features implemented within the GraphQL layer of the API, including types, queries, mutations, resolvers, directives, scalars, and error handling. ```apidoc GraphQL Features: - Types - Queries - Mutations - Resolvers - Directives - Scalars - Plugins - Error Handling ``` -------------------------------- ### Git Features Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md Outlines the Git functionalities utilized in the project, such as aliases, custom logs, branching, resetting, amending, tagging, stashing, rebasing, and merging. ```apidoc Git Features: - Alias - Custom Log - Branch - Reset - Amend - Tag - Stash - Rebase - Merge ``` -------------------------------- ### MongoDB Features Source: https://github.com/rmanguinho/clean-ts-api/blob/master/readme.md Details the MongoDB operations and features used, including connection management, collections, CRUD operations (insert, find, update, delete), aggregation pipeline, and ObjectId handling. ```apidoc MongoDB Features: - Connect and Reconnect - Collections - InsertOne and InsertMany - Find, FindOne, and FindOneAndUpdate - DeleteMany - UpdateOne - Aggregation (Match, Group, Unwind, Lookup, AddFields, Project, Sort) - ObjectId - Upsert and ReturnOriginal - Operators (Push, Divide, Multiply, ArrayElemAt, Cond, Sum) - Document Manipulation (Filter, Map, Reduce, MergeObjects, ConcatArrays) ``` -------------------------------- ### API: Criar Enquete Source: https://github.com/rmanguinho/clean-ts-api/blob/master/requirements/add-survey.md Define o endpoint para criação de enquetes. Espera uma requisição POST na rota /api/surveys, validando se o usuário é um admin e se os campos 'question' e 'answers' estão presentes. Retorna 204 em caso de sucesso, ou códigos de erro apropriados (404, 403, 400, 500) para falhas. ```APIDOC POST /api/surveys Request: Headers: Authorization: Bearer (Admin) Body: question: string (obrigatório) answers: array of strings (obrigatório) Responses: 204 No Content: Enquete criada com sucesso. 400 Bad Request: 'question' ou 'answers' não fornecidos. 403 Forbidden: Usuário não é admin. 404 Not Found: Rota da API não encontrada. 500 Internal Server Error: Erro ao criar a enquete. ``` -------------------------------- ### Survey Response API Source: https://github.com/rmanguinho/clean-ts-api/blob/master/requirements/save-survey-result.md Handles the creation and updating of survey results via a PUT request. It validates user authentication, survey ID, and the provided answer. Returns success status or specific error codes for various failure conditions. ```APIDOC PUT /api/surveys/{survey_id}/results Description: Handles the creation or update of survey results. Request: - Validates if the request is made by an authenticated user. - Validates the `survey_id` parameter in the URL. - Validates if the `answer` field is a valid response. - Creates a survey result if no record exists. - Updates a survey result if a record already exists. Responses: - 200 OK: Successfully created or updated survey result. - 404 Not Found: API endpoint does not exist. - 403 Forbidden: - Request not made by an authenticated user. - Invalid `survey_id` provided. - Invalid `answer` provided. - 500 Internal Server Error: - Error creating survey result. - Error updating survey result. - Error loading survey. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.