Skip to content

roxxydev/fastify-basic-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

An example api server using Fastify. This uses JWT (JSON Web Token) for authorization and has implemented RBAC (Role-Based Access Control) for restrict and control what resources can only access. It has a fastify plugin store which allows server to switch between ORM/ODM (Knex, Mongoose) giving option of using either SQL databases supported by Knex or MongoDB of Mongoose.

Project setup

npm install

npm start

Start fastify server config values set in .env file

npm test

Create database named testdb in Postgres. Run test script. By default the test script uses the Lab of Hapi. To use Tap in test script, simply declare TEST_USE_TAP in .env file and set to true.


Structure

  • server.js - Creates fastify server instance.
  • routes/services/ - Contains logic needed of routes.
  • routes/api/ - Routes of fastify.
  • routes/api/*/schemas.js - Contains validation schemas using fluent-schema.
  • utils - Contains utility methods.
  • setup - Script setup before starting server. Initially contain setup for creating data like roles and scopes to database.
  • enviroment - Configuration values.
  • plugins - Contains fastify plugins.
  • plugins/store.js - Fastify plugin creting store server property that have interface for database CRUD operations wrapper for either using Knex or Mongoose.
  • models - Contains database related schemas, properties and operations.
  • models/model.js - Contains property name and values used in database schema.
  • models/roles.js - Initial roles used in this API.
  • models/scope.js - Initial scopes used in this API.
  • models/operations/ - Interface implementation of CRUD database transactions. Each filename represent the name of the table/schema which also matches the model name defined in model.js.
  • migrations - Contains migration scripts used in knex.
  • schemas - Contains model schemas for moongose.

API Documentation

The project implements fastify-swagger for creating Swagger documentation to route /documentation.


Example

Create account passing basic account information.

curl --header "Content-Type: application/json" --request POST --data '{"username":"foo10001","password":""}' http://localhost:8088/api/v0/account/register
  • Request:
POST /api/v0/account HTTP/1.1
Accept: application/json
Content-Type: application/json

{
    "username": "foo10001",
    "password": "P@ssw0rd"
}
  • Response:
HTTP/1.1 200 OK
Content-Type: application/json

{
   "id": 1,
   "username": "foo10001",
   "created_at": "2020-10-04T16:00:07.726Z"
}