General setup for entities

Explanation on how to setup entities for automagic and use in Primate

Entities are concepts inside your project that will have at least:

  • Storage in database

  • Enpoints to read, write, update or delete

In this manner, to have an entity we need a group of things described in the following article.

Database Model

For Primate, our ORM is Prisma. In this manner, the database model should exist inside the schema.prisma.

Routes

For the entity to be consumed we need at least one route. In primate, there is a default way to give your entity CrUD capabilities. This can be achieved doing the following:

  1. Create an /entitites folder in the root of your project

  2. Create a folder with the plural name of your entity, for example: /entities/users

  3. Create a file called /entities/[plural/][plural].js for your routes, for example: /entities/users/users.js

  4. Finally, add your routes inside the file in the following way:

import { auth, Primate } from '@thewebchimp/primate';
const router = Primate.getRouter();

router.get('/foo', (req, res) => {
    res.respond({
        data: 'bar'
    });
});

export { router };

This will give the following response when typing http://localhost:1337/[plural]/foo:

{
  "result": "success",
  "status": 200,
  "data": "bar",
  "message": ""
}

Automagic CrUD routes

Part of the automagic of Primate is that it gives automatically a way to Create, Update and Delete entities. To setup the automagic CrUD, you need the following code in your route file:

import { auth, Primate } from '@thewebchimp/primate';
const router = Primate.getRouter();

Primate.setupRoute('[singular]', router);

export { router };

This will give you automatically the following routes:

  • GET /[plural] for listing all elements

  • GET /[plural]/:id for geting one element

  • POST /[plural] for creating one element

  • PUT /[plural]/:id for updating one element

  • DELETE /[plural]/:id for deleting one element

  • GET /[plural]/:id/metas for getting the metas of one element

Services

Last updated