Skip to content

Instantly share code, notes, and snippets.

@cami-la
Last active February 13, 2024 13:11
Show Gist options
  • Save cami-la/c8d5f41f28cc8dccfcb98f4aff055134 to your computer and use it in GitHub Desktop.
Save cami-la/c8d5f41f28cc8dccfcb98f4aff055134 to your computer and use it in GitHub Desktop.
Configuração Inicial Projeto Node.Js + TypeScript + Express + Mongoose

Este gist foi criado com o intuito de facilitar a inicialização de um novo projeto de software utilizando as seguintes tecnologias: Node.js, TypeScript, Express e Mongoose.

Configuração Inicial Projeto Node.Js + TypeScript + Express + Mongoose

Movie gif. Aaron Ruell as Kip in Napoleon Dynamite slouches as he sits back and types on a keyboard as if working.

O que aprenderemos nesta aula:

  1. Setup Inicial Projeto Node.Js + TypeScript
  2. Setup Inicial Express + TypeScript
  3. Setup Inicial Mongoose + Typescript

  • Node.js: Um ambiente de execução JavaScript que permite executar código JavaScript no servidor.
  • TypeScript: Uma linguagem que adiciona tipagem estática ao JavaScript, trazendo benefícios de produtividade e escalabilidade ao código.
  • Express: Um framework web para Node.js que simplifica o desenvolvimento de aplicativos web e APIs.
  • Mongoose: Uma biblioteca ODM (Object Data Modeling) para MongoDB e Node.js, proporcionando uma maneira mais simples de interagir com o banco de dados MongoDB.

Pré-requisitos

Antes de começar, certifique-se de que você tenha os seguintes pré-requisitos instalados em sua máquina:

  1. IDE ou Editor de Código: Recomendo o uso de uma IDE (Integrated Development Environment) ou editor de código. Neste projeto, utilizei a WebStorm, mas você pode escolher a que preferir, como VSCode, Atom, Sublime, etc.

  2. Node.js: É necessário ter o Node.js instalado em sua máquina. Recomendo a versão 21.4.0 ou superior. Você pode baixar o Node.js em nodejs.org.

  3. Yarn ou Npm: Utilizei o Yarn como ferramenta de gerenciamento de dependências. Certifique-se de tê-lo instalado. Você pode instalar o Yarn seguindo as instruções em yarnpkg.com. Se preferir, você pode optar pelo npm, o gerenciador de pacotes padrão do Node.js.

  4. Git: O Git é essencial para o controle de versão. Certifique-se de tê-lo instalado e configurado em sua máquina. Você pode baixar o Git em git-scm.com.

  5. GitHub: Utilizei o GitHub para o controle de versão e hospedagem do código-fonte deste projeto. Você pode criar uma conta gratuita no GitHub e seguir as instruções para criar seu repositório. outras opções: GitLab, Bitbucket, AWS CodeCommit ou Azure DevOps.

  6. Conta no MongoDB Atlas: Este projeto utiliza o MongoDB como banco de dados. Certifique-se de ter uma conta no MongoDB Atlas e crie um cluster para armazenar seus dados.

  7. Postman: Utilizei o Postman como ferramenta de teste de APIs neste projeto. Você pode baixá-lo em postman.com. Outras opções incluem Insomnia, cURL, ou HTTPie.

Nota: Os comandos fornecidos são específicos para ambientes baseados em Linux e Yarn. Por favor, ajuste conforme necessário se estiver utilizando um sistema operacional ou ferramenta de gerenciamento de dependências diferentes.

🩵 Setup Inicial Projeto Node.Js + TypeScript

No Terminal/Cmd

  1. Criar uma pasta para o projeto: mkdir <nome-da-pasta>
  2. Entrar na pasta criada e iniciar o projeto Node.js: yarn init --y
  3. Adicionar as dependências iniciais de desenvolvimento com Typescript: yarn add -D typescript ts-node ts-node-dev @types/node
  4. Criar o arquivo de configuração TypeScript (tsconfig.json): tsc --init
  5. Criar a pasta principal do projeto e criar o arquivo principal: mkdir src && cd src && echo 'console.log("Hello World")' > index.ts

Na IDE/Editor de Código:

  1. Abrir o arquivo package.json e adicionar os scripts para rodar o projeto em ambiente de desenvolvimento:
"scripts": {
    "dev": "ts-node-dev --respawn src/**.ts",
}
  1. Setar suas preferências do TypeScript no arquivo tsconfig.json:
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Enable incremental compilation */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2021",
    /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
    // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */

    /* Modules */
    "module": "commonjs",
    /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",
    /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    "rootDirs": [
      "src"
    ],
    /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "resolveJsonModule": true,                        /* Enable importing .json files */
    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./dist",
    /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,
    /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,
    /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,
    /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
    // "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
    // "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true
    /* Skip type checking all .d.ts files. */
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ],
  "ts-node": {
    "files": true
  }
}
  1. No terminal/cmd, execute o comando: yarn dev
  2. git add . && git commit -sm "Configurações iniciais node.js + ts"

🩶 Setup Inicial Express + TypeScript

No Terminal/cmd:

  1. Adicionar a dependência de produção: yarn add express
  2. Adicionar as dependências de desenvolvimento: yarn add -D @types/express dotenv
  3. Criar o arquivo .env para configuração de variáveis de ambiente: echo 'PORT="3000"' > .env
  4. Dentro do diretório src, crie um diretório routes, com o arquivo index.ts: cd src && mkdir routes && touch routes/routes.ts && cd ..

Na IDE/Editor de código

  1. Alterar o arquivo index.ts para iniciar o servidor Express:
import express, {Express} from "express"
import 'dotenv/config'

const PORT: string = process.env.PORT || '3000'

const app: Express = express()
app.use(express.json())

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
})
  1. No terminal/cmd, execute o comando: yarn dev

  2. Criar a primeira rota de teste no arquivo index.ts no caminho src/routes/index.ts:

import {Router} from 'express'

const router = Router()

router.get('/', async (_, res) => {
	return res.status(200).send('Hello World!')
})

export {router}
  1. Indicicar o uso das rotas no arquivo principal index.ts:
import express, {Express} from "express"
import 'dotenv/config'

const PORT: string = process.env.PORT || '3000'

const app: Express = express()
app.use(express.json())
app.use(router) //here

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
})
  1. No terminal/cmd, execute o comando: yarn dev
  2. git add . && git commit -sm "Configurações iniciais Express + ts"

💚 Setup Inicial Mongoose + Typescript

Obter a string de conexão do banco de dados (criei um BD no MongoDB Atlas)

No Terminal/cmd

  1. Adicionar as dependência do mongoose e seus types: yarn add mongoose && yarn add -D @types/mongoose
  2. Criar o arquivo mongo-cnct.ts para definir a conexão com o MongoDB: cd src && mkdir database && touch database/mongo-cnnct.ts && cd ..

Na IDE/Editor de código

  1. Acrescentar a string de conexão do banco de dados no arquivo .env
MONGODB_URI=mongodb+srv://<USER>:<SENHA>@urlshortenerdemo.af0ruba.mongodb.net/urlshortenerdemo?retryWrites=true&w=majority
  1. Definir a conexão do mongoose no arquivo src/database/mongo-cnnct.ts:
import mongoose from 'mongoose'

const MONGODB_URI: string = process.env.MONGODB_URI || ''

export const runMongo = () => {
  mongoose.connect(MONGODB_URI)
    .then(() => console.log('Connected to MongoDB'))
    .catch((err: Error) => console.error('Error connecting to MongoDB', err))
}
  1. Chamar a execução do mongo no arquivo principal index.ts:
import express, {Express} from "express"
import 'dotenv/config'
import {runMongo} from "./database/mongo-cnnct";

const PORT: string = process.env.PORT || '3000'

const app: Express = express()
app.use(express.json())
app.use(router)

runMongo() //here

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
})
  1. No terminal/cmd, execute o comando: yarn dev
  2. git add . && git commit -sm "Configurações iniciais Mogoose + ts"

Estrutura do Projeto a partir do diretório /src:

.
├── database
│   └── mongo-cnnct.ts
├── index.ts
└── routes
    └── index.ts

Charlie Hunnam Reaction GIF


< ANTERIOR | PRÓXIMO >

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment