Celebrating 10 years in web hosting [email protected]

How to set up crud in ADONISJS

AdonisJS: how to run a simple CRUD operation? In this article, we will install the Adonis.Js and I will try to help you get started with Adonisjs by executing an API CRUD operation.

Now we are going to develop a simple Post module.

You can purchase your hosting from Cloudsurph.comCloudsurph hosting is a reliable hosting option for business and personal projects. We offer insight and help on system configuration issues and code errors or bugs.

Installation

Step 1

npm init adonis-ts-app@latest simple-crud

Step 2

Now we need to Select the project structure

❯ api   (Tailored for creating a REST API server)
  web   (Traditional web application with server rendered templates)
  slim  (A smallest possible AdonisJS application)

Step 3

Go to the created project directory

cd simple-crud

Database configuration

Step 1

Here, installs lucid additional package for working with database into AdonisJS

npm i @adonisjs/lucid

Step 2

Now, you need to create the necessary configuration files (No need to do extra things only run the below command)

node ace configure @adonisjs/lucid

Step 3

So, here selects the database provider you want to use, we use MYSQL here

◯ SQLite
◉ MySQL / MariaDB
◯ PostgreSQL
◯ OracleDB
◯ Microsoft SQL Server

Step 4

Now, need to provide your MYSQL database information in the .env file below

DB_CONNECTION=mysql

MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=simple_crud
MYSQL_PASSWORD=demo
MYSQL_DB_NAME=demo

Migration

Step 1

IF you want then buy a good, reliable, secure web hosting service  from here: click here

Now, need to create a migration file and provide the table name with the columns you prepared.

node ace make:migration posts

So now, navigate to your database > migration directory you will find a file created with the name of posts.

adonisjs-simple-crud

Step 2

Here, you need to provide the columns that you want to add to the posts table.

  public async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.increments("id");

      table.string("title").notNullable();
      table.text("content").notNullable();

      //   Other columns ...

      table.timestamp("created_at", { useTz: true });
      table.timestamp("updated_at", { useTz: true });
    });
  }

Step 3

Now, run the migration command to create tables in your database

node ace migration:run

After successful migration, you will get the following message as like below

[ info ]  Upgrading migrations version from "1" to "2"
❯ migrated database/migrations/1655556358714_posts

Migrated in 235 ms

Model

Step 1

After migration, need to create a model for your database table

node ace make:model Post

The model will be created at app/Models/User.ts

Step 2

Now, pen your model file and add the necessary columns at your model

export default class Post extends BaseModel {
  @column({ isPrimary: true })
  public id: number;

  @column()
  public title: string;

  @column()
  public content: string;

  // Other columns ...

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime;

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime;
}

Controller

Step 1

Here, you need to create the post controller using the below command

node ace make:controller Post

Step 2

Open your created controller and define the methods there

Show all posts

public async showAll({ response }: HttpContextContract) {
    const posts = Post.all();
    
    return posts;
}

Show the single post

public async show({ response, params }: HttpContextContract) {
    const post = await Post.find(params.id);
    response.abortIf(!post, "Post not found", 404);
    return response.json(post);
}

Create post

public async create({ request, response }: HttpContextContract) {
    const payload = await request.validate({
        schema: schema.create({
        title: schema.string(),
        content: schema.string(),
        }),
    });

    const post = await Post.create(payload);

    return response.json(post);
}

Update post

public async update({ request, response, params }: HttpContextContract) {
    const post = await Post.find(params.id);

    response.abortIf(!post, "Post not found", 404);

    const payload = await request.validate({
        schema: schema.create({
        title: schema.string(),
        content: schema.string(),
        }),
    });

    const updatedPost = await Post.updateOrCreate({ id: params.id }, payload);

    return response.json(updatedPost);
}

Delete post

public async delete({ request, response, params }: HttpContextContract) {
    const post = await Post.find(params.id);

    response.abortIf(!post, "Post not found", 404);

    post?.delete();

    return response.json({});
}

Finally, our controller file must look like this

import type { HttpContextContract } from "@ioc:Adonis/Core/HttpContext";
import { schema } from "@ioc:Adonis/Core/Validator";
import Post from "App/Models/Post";

export default class PostsController {
  // GET /post/:id
  public async show({ response, params }: HttpContextContract) {
    const post = await Post.find(params.id);
    response.abortIf(!post, "Post not found", 404);
    return response.json(post);
  }

  // GET /post
  public async showAll({ response }: HttpContextContract) {
    const posts = Post.all();
    return posts;
  }

  // POST /post
  public async create({ request, response }: HttpContextContract) {
    const payload = await request.validate({
      schema: schema.create({
        title: schema.string(),
        content: schema.string(),
      }),
    });

    const post = await Post.create(payload);
    return response.json(post);
  }

  // PUT /post/:id
  public async update({ request, response, params }: HttpContextContract) {
    const post = await Post.find(params.id);
    response.abortIf(!post, "Post not found", 404);

    const payload = await request.validate({
      schema: schema.create({
        title: schema.string(),
        content: schema.string(),
      }),
    });

    const updatedPost = await Post.updateOrCreate({ id: params.id }, payload);
    return response.json(updatedPost);
  }

  // DELETE /post/:id
  public async delete({ request, response, params }: HttpContextContract) {
    const post = await Post.find(params.id);
    response.abortIf(!post, "Post not found", 404);
    post?.delete();
    return response.json({});
  }
}

Routing

Now, add routes to the start > routes.ts file

Route.get("/post", "PostsController.showAll");
Route.get("/post/:id", "PostsController.show");
Route.post("/post", "PostsController.create");
Route.put("/post/:id", "PostsController.update");
Route.delete("/post/:id", "PostsController.delete");

And finally, that’s it.

Now we can run the adonis js application with the below simple command

node ace serve --watch

Your app will simply be available at http://127.0.0.1:3333

Open PostMan or similar software and access the routes.

If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.