📜 TypeScript Project Template for Back End Development

Overview

Logo

TypeScript Project Template

Back End Development Project Template
Browse TypeScript code»

Built With


Table of Contents

Installation and Usage

Pre-requisites: Node.js ^16.14.0, TypeScript ^4.7.4

There are two available options for you to use this template for your next Back End project: either use Github's built-in Use this template feature (green button left of the 'About' section), or download the zip file and extract it in the root of a new project folder by running these commands:

wget https://github.com/NivaldoFarias/typescript-project-template/archive/main.zip

Then run the following command to install the project's dependencies:

npm install

That's it! You can now start developing your TypeScript Project by running the command below. Happy coding!

npm run dev
ps.: Make sure to update the package.json file with your own credentials!

Error Handling and Logging

While dealing with errors in a Layered Structure Project enviroment, you may notice that the project's debugging complexity scales beyond common console.log() usage. The AppLog Object and AppError Object structures were set to counter that exact issue, by trying to keep the Development process as clean and concise as possible. Both are frequently referenced in the code, but do have a specific usage.

▸   AppError

An AppError Object is used to handle errors in the application. It that takes four parameters:

  • log: A string containing a simplified error message, for Server side use. This is the message that will be used by the AppLog Object
  • statusCode: An integer containing the HTTP status code.
  • message: A string containing a simplified error message, for Client side use. This is the message that will be displayed to the user.
  • details: A string containing a detailed error message, for Client side use. Can be used to provide more information about the error, such as the stack trace, or suggestions on how to counter the error.
Example Usage
  // ..../middlewares/auth.middleware.ts

  import * as repository from './../repositories/auth.repository.ts';
  import AppError from './../events/AppError';
  ...
  ..

  async function usersExists(req: Request,...){
    ...
    ..
    const user = await repository.findbyId(req.body.id);

    if (!user){
      throw new AppError(
        'User not found',
        404,
        'User not found',
        'Ensure to provide a valid user ID.'
      );
    }
    ..
    ...
  }

▸   AppLog

An AppLog Object is used to handle logs in the application. It takes two parameters:

  • type: A string containing the main Layer Structure that contains the log. There are seven allowed values: Error, Server, Controller, Middleware, Repository, Service, and Util.
  • text: A descriptive string containing the log message. Generally, a short message that describes the output event of the function that generated the log.
Example Usage
  // ..../middlewares/auth.middleware.ts

  import AppLog from './events/AppLog';
  ...
  ..

  async function usersExists(req: Request,...){
    ...
    ..

    // output: [Middleware] User Found
    AppLog('Middleware', 'User found');
    res.locals.user = user;
    return next();
  }
  ..
  ...
ps.2: Have fun with these structures! They are in no way restricted to the project's scope

Middlewares

While aiming to provide a reusable, modular and extensible architecture, the middlewares are generally the first structures to be refactored into self-contained modules. The validateSchema(), processHeader() and requireToken() middlewares were set in order to achieve that goal. The following section describes useMiddleware(), which incorporates the forementioned functions as key–value pairs in an Object, along with their structure and usage.

‣  UseMiddleware

The useMiddleware() function takes two parameters:

  • middlewares: An Object containing the key–value pairs of the middlewares to be used, takes one to three parameters:
    • schema: A Joi Schema Object that will be used to validate the data provided by the client. If the data provided by the client is not valid, an AppError Object will be thrown.
    • header: A string containing the name of the header that will be used to authenticate the action. If the client-provided header is missing, an AppError Object will be thrown.
    • token: A boolean indicating whether the token provided by the client will be verified or not. If the token is not valid, an AppError Object will be thrown.
  • endpoint: A string that will be used to identify the endpoint at which the client–api interaction is undergoing, which will be logged to console by the AppLog Object.
Reference: useMiddleware function declaration
Example Usage
// ..../routes/admin.route.ts
import useMiddleware from '../utils/middleware.util';
import * as schema from '../models/admin.model';
...
..
const endpoint = '/admin';

const registerEndpoint = '/create';
adminRouter.post(endpoint,
  createEndpoint,
  useMiddleware({
    schema: schema.create,
    header: 'admin-api-key',
    token: true
  },
  endpoint + createEndpoint),
  middleware.createValidations,
  controller.create,
);
..
...

API Reference

In this section, you will find the example API's endpoints and their respective descriptions, along with the request and response examples, as well as the Prisma models for each entity, that can be used as guide for data formatting. All data is sent and received as JSON.

Models

User model users

  • id: A unique identifier for each user. serial4
  • username: The user's username. text
  • email: The user's email. An email may only be registered once. text
  • password: The user's password. text
  • created_at: The date and time when the user was created. timestamp

Routes

Authentication /auth

Authentication

  ‣   Register

    POST /auth/register

  ☰   Request

Body
{
  "username": "johndoe",
  "email": "[email protected]",
  "password": "123456789"
}
Headers
{
  "Content-Type": "application/json"
}

  ☰   Responses

Status Code Description Properties
201 Created data: {}
409 Email already registered error: { message, details }
422 Invalid Input error: { message, details }
500 Internal Server Error error: { message, details }

  ‣   Sign in

    POST /auth/sign-in

  ☰   Request

Body
{
  "email": "[email protected]",
  "password": "123456789"
}
Headers
{
  "Content-Type": "application/json"
}

  ☰   Responses

Status Code Description Properties
200 OK data: { token }
403 Invalid password error: { message, details }
404 User not found error: { message, details }
422 Invalid Input error: { message, details }
500 Internal Server Error error: { message, details }

Template created by Nivaldo Farias.
You might also like...

A NPM package powered by Yeoman that generates a scaffolding boilerplate for back-end workflow with Node.js.

generator-noderplate Generate Node.js starter files with just one command! We have deployed a npm package that will generate a boilerplate for nodejs

Jan 24, 2022

School App / Back-End with MongoDB / mongoose / Express / TS

TEST Api Dependencies El mati se la come es por eso que en 1998 la guerra fria se llevo a mas de la mitad del activo del pais "dependencies": { "axios

Jun 10, 2022

Uma aplicação back-end para listar e verificar se o dia é um feriado de acordo com os feriados registrados no sistema

Holydayzer Sobre Uma aplicação back-end para listar e verificar se o dia é um feriado de acordo com os feriados registrados no sistema. Como rodar Exe

Mar 9, 2022

Uma aplicação back-end para consumo e envio de frases/mensagens semelhante ao twitter.

Tweteroo Uma aplicação back-end utilizando o nodemon para rodar o servidor e o express para consumo e envio de frases/mensagens. Rodar projeto Após cl

Feb 3, 2022

A back-end web app allows you to register and login to access a secrets page

A back-end web app allows you to register and login to access a secrets page

Oct 30, 2022

This shows NFT tracking in the certain wallet using express back-end.

nft-tracking-for-solana-wallet Express backend for NFT tracking in the certain wallet. Webhook for scraping secondary marketplace information for part

Nov 16, 2022

E-commerce Back-end Server

Ecommerce Backend Server This project contains the intial setup needed for creating the MVC folder for our Ecommerce-backend application and setting u

Feb 10, 2022

Deploying Fake Back-End Server & DataBase Using JSON-SERVER, GitHub, and Heroku

Deploying Fake Back-End Server & DataBase Using JSON-SERVER, GitHub, and Heroku

Deploying Fake Back-End Server & DataBase Using JSON-SERVER, GitHub, and Heroku. In this article, we will create and host a fake server that we can de

Sep 5, 2022

stackoverflow back end clone with node.js

stackoverflow back end clone with node.js

Stackoverflow clone with Node.js Run To run this project, download it to your computer and open it with a code editor. Open the .env file in the env f

Nov 20, 2022
Releases(v2.0.0)
  • v2.0.0(Jul 25, 2022)

    The Template went through several significant updates, upgrades and received further additions to improve performance.

    Wha's new

    Prisma

    References: client Object instancing, prisma files

    As a Developer, using new, optmized, softwares is key in order to achieve a smooth-sailing to the final product. Switching PG packages and softwares to Prisma is a decision based on that principle. A new project based on this template may now utilize Prisma broad functionalities with ease, since all structural implementations are already set.

    The database instancing does not change significantly, the client Object declaration is the main difference. With Prisma, the Object uses their built-in semantics and syntax, which must be in line with their documentation.

    useMiddleware function

    References: middleware function declaration, schema middleware, header middleware, token middleware

    In previous versions, the provided global middlewares function were validateSchema() and processHeader(). This version iterates upon these functions and creates an Object that incorporates both of these middlewares as key-value pairs, as well as implements a new middleware funtion, requireToken(), to be used when a JSON web token signature must be validated.

    > The previous implementation of the middlewares (validateMiddleware and processHeader) is deprecated.

    Example API Documentation

    References: README file

    To ease new users or contributors into using the API, a well-written, intuitive, and comprehensive Documentation is crucial. The example Docs serves as template for further iterations upon the API's functionalities, which may encompass new Layers into the project's Layered Structure.

    Utils and Types folders

    References: types folder, utils folder

    An expansion within the template's folder structure was needed during the iterations upon the forementioned topics. To better modularize the new functionalities, these structures were built. The main addition is the constants file, which incorporates all recurrent constants, globals and enviroment variables into partial Objects that can be imported individually to code.

    Source code(tar.gz)
    Source code(zip)
Owner
Nivaldo Farias
Full Stack Development Student
Nivaldo Farias
Personal Blog - a project developed with Angular for the front-end interface and Wordpress for the back-end API served with Docker containers

PersonalBlog This project was generated with Angular CLI version 13.0.1. Front-end Interface Development server Run ng serve or ng serve --configurati

null 9 Oct 5, 2022
It consists of a recreation of Twitter, to put into practice both Front-end and Back-end knowledge by implementing the MERN Stack together with other technologies to add more value to the project.

Twitter-Clone_Back-end ✨ Demo. ?? About the project. ?? Descriptions. It consists of a recreation of Twitter, to put into practice knowledge of both F

Mario Quirós Luna 5 Apr 12, 2022
It consists of a recreation of Twitter, to put into practice knowledge of both Front-end and Back-end implementing the MERN Stack along with other technologies to add more value to the project.

Twitter-Clone_Front-end ✨ Demo. Login Home Profile Message Notifications Deployed in: https://twitter-clone-front-end.vercel.app/ ?? About the project

Mario Quirós Luna 5 Jun 26, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Pass trust from a front-end Algorand WalletConnect session, to a back-end web service

AlgoAuth Authenticate to a website using only your Algorand wallet Pass trust from a front-end Algorand WalletConnect session, to a back-end web servi

Nullable Labs 16 Dec 15, 2022
End-to-end typed monorepo template for your next project ⌨️

TYPE ⌨️ TRPC + Yarn Monorepo + Prisma + Expo This template project is a Yarn monorepo with full end-to-end type safety. Powered by: TRPC (on Fastify)

Matteo Lobello 35 Oct 22, 2022
Back-end desenvolvido com NodeJS, TypeScript, Prisma e Express para prover dados para as aplicações em desenvolvimento.plicações do evento NLW eSports.

NLW eSports Back-End Aplicação back-end para surprir as necessidades de dados das demais plataformas desenvolvidas que são citadas mais abaixo. Este s

Felippe Rian 2 Sep 17, 2022
RESTful API using Hapi NodeJs Framework. This app is project from Dicoding Couses, Belajar Membuat Aplikasi Back-end untuk Pemula

RESTful API using Hapi NodeJs Framework. This app is project from Dicoding Couses, Belajar Membuat Aplikasi Back-end untuk Pemula

Muhammad Ferdian Iqbal 1 Jan 3, 2022