strapi series--teach you in detail how to build a table and rewrite the original query, modification and other interface logic on the basis of the original official automatically generated api, covering the official original default return logic

Why backend customization?

In the process of using strapi, we can use the methods stipulated in official documents to build tables and look up tables for most of the requirements in the project, but sometimes we need to customize our own business logic, so how should we deal with this requirement? This article covers the official find, findOne and other methods in the form of pictures and texts, and customizes a business logic interface of our own.

Every part of the Strapi backend can be customized

  • The request received by the Strapi server
  • Routes that handle requests and trigger controller handler execution
  • Policies that can block access to a route
  • Middleware can control the request flow and request before moving forward
  • A controller that executes code once a route is reached
  • Services for building reusable custom logic for controllers
  • A model is a representation of the content data structure
  • The response sent to the application

Data preparation, quick start

Create a new table cake-info

Create three new fields

Insert a few pieces of data

Set permissions (temporarily set to public interface)

test interface

Request URL:
http://localhost:1337/api/cake-infos
Request Method:
GET
Default data format:

Rewrite the original find, findOne

At present, we access the interface and use the factory function to return the data structure by default. If we want to add custom logic, we need to rewrite src/api/cake-info/controllers/cake-info.js

Rewrite /api/cake-infos

  • official document
  • This interface corresponds to the default find method, we need to modify the src/api/cake-info/controllers/cake-info.js file as follows:

Original file:

'use strict';

/**
 * cake-info controller
 */

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::cake-info.cake-info');

Use await super.find(ctx) to override the find method in src/api/cake-info/controllers/cake-info.js

"use strict";

/**
 * cake-info controller
 */

const { createCoreController } = require("@strapi/strapi").factories;

module.exports = createCoreController(
  "api::cake-info.cake-info",
  ({ strapi }) => ({
    async find(ctx) {
      const { data, meta } = await super.find(ctx);

      return { statuss: "success", code: 1, data, meta };
    },
  })
);


test rewrite logic

Factory api rewriting - keep the core logic

find

async find(ctx) {
  // some logic here
  const { data, meta } = await super.find(ctx);
  // some more logic

  return { data, meta };
}

findOne

Wrap core actions (keep core logic)

async findOne(ctx) {
  // some logic here
  const response = await super.findOne(ctx);
  // some more logic

  return response;
}

You can also call a custom service, completely custom logic, like this:


const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::restaurant.restaurant', ({ strapi }) =>  ({
  async findOne(ctx) {
    const sanitizedQueryParams = await this.sanitizeQuery(ctx);
    const { results, pagination } = await strapi.service('api::restaurant.restaurant').find(sanitizedQueryParams);
    const sanitizedResults = await this.sanitizeOutput(results, ctx);

    return this.transformResponse(sanitizedResults, { pagination });
  }
}));

create

async create(ctx) {
  // some logic here
  const response = await super.create(ctx);
  // some more logic

  return response;
}

Directly rewrite find, etc. and call custom service

For example,
src/api/test-type/controllers/test-type.js

'use strict';

/**
 * test-type controller
 */

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::test-type.test-type', ({ strapi }) => ({
  async findOne(ctx) {
    try {
      const { data } = await super.findOne(ctx);
      const result = await strapi.services['api::test-type.test-type']['testInfo'](
        data,
        ctx.query,
      );
      ctx.success(result);
    } catch (err) {
      strapi.log.error(err.message);
      ctx.fail(err.message);
    }
  },
  async find(ctx) {
    try {
      const result = await strapi.services['api::test-type.test-type']['testCatagory'](
        ctx.query.lang,
      );
      ctx.success(result);
    } catch (err) {
      strapi.log.error(err.message);
      ctx.fail(err.message);
    }
  },
}));

Directly call the method encapsulated by strapi to read the database

give a chestnut

const data = await strapi.db.query('api::test-type.test-type').findOne({
  where: {
    id: query.id,
  },
  populate: {
    relation: true,
    tests: {
      populate: ['test_tags', 'test_detail', 'test_types'],
    },
  },
});

You're done~~

  • That’s all for today~ Friends, ( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ See you tomorrow~~
  • Everyone be happy every day

Everyone is welcome to point out where the article needs to be corrected~
Learning is endless, cooperation is win-win

insert image description here

Welcome the little brothers and sisters passing by to put forward better opinions~~

おすすめ

転載: blog.csdn.net/tangdou369098655/article/details/131485486