Strapi headless CMS use and custom configuration
Introduction to headless CMS
A headless CMS is built from the bottom up as a content repository, making a back-end content management system (CMS) accessible by displaying a RESTful API content on any device.
The term “headless” comes from the concept of cutting off the “head” (the front end, the website) from the “body” (the back end, the content repository). A headless CMS retains an interface for adding content, as well as RESTful apis (JSON, XML) to deliver content when needed. Because of this approach, a headless CMS doesn’t care how or where the content is displayed. Headless CMS has only one focus: storing and delivering structured content.
The corresponding part of a headless CMS is often referred to as an integrated, regular, or coupled CMS, and we’ll use those terms later
The CMS system structure is as follows
To convert the above into a headless CMS, we simply remove function four from the stack. The head of the CMS – the actual site – was axed. All that is left is an application that allows content management (Admin UI) and reading (API: composite integration).
Creating an entire site on its own might seem like a tall order on the list, but by separating the CMS from the front end, developers can choose whatever technology they are already familiar with without having to learn the technology of a particular CMS. Another big benefit is the fact that a developer can also focus on their own work and not deal with the bug that the technology already exists in the stack.
Strapi is a feature-rich headless CMS open source project built 100% in javascript with developer-friendly and customizable features.
Strapi use
- Install StrAPI and create a new project
# Using Yarn
yarn create strapi-app my-project --quickstart
# Or using NPM
npx create-strapi-app my-project --quickstart
Copy the code
- Configuring the Database
Strapi support
- Mongo > = 3.6
- MySQL > = 5.6
- MariaDB > = 10.1
- PostgreSQL >= 10
- SQLite >= 3
Configure the database used in the strAPI project directory /config/database.js
module.exports = ({ env }) = > ({
defaultConnection: 'default'.connections: {
default: {
connector: 'bookshelf'.settings: {
"client": "mysql"."database": env.DATABASE,
"host": env.HOST,
"port": env.PORT,
"username": env.USERNAME,
"password": env.PASSWORD
},
options: {
useNullAsDefault: true,},},},});Copy the code
- Create a content
Strapi. IO /documentati strapi. IO /documentati
Strapi custom plug-in
strapi generate:plugin import-content
Copy the code
Executing the above command will generate an import-content plug-in on the strAPI project in the /plugins/import-content directory. Directory structure is as follows – | admin/SRC internal to the admin panel displays the contents of the plugin – | controllers control layer — – | | services service layer. Editorconfig — |. Gitattributes –|.gitignore –|package.json –|README.md
Directory structure for the MVC structure, view the call control layer, or page under/admin/SRC (containers under the entry page is located in the SRC/HomePage/index. Js)
import {request} from "strapi-helper-plugin";
// preAnalyzeImportFile Specifies the controller method for the control layer
const response = await request("/import-content/preAnalyzeImportFile", {
method: "POST".body: {
/ / request body}});Copy the code
The preAnalyzeImportFile method called by the controllers/import-content.js looks like this:
'use strict';
/**
* import-content.js controller
*
* @description: A set of functions called "actions" of the `import-content` plugin.
*/
module.exports = {
/**
* Default action.
*
* @return {Object}* /
preAnalyzeImportFile: async ctx => {
// Get the service
const services = strapi.plugins["import-content"].services;
try {
// The controller calls the preAnalyzeImportFile method of the import-Content. js service in the service to request data or other operations
const rightFile = await services["import-content"].preAnalyzeImportFile(ctx);
ctx.send(rightFile);
} catch (error) {
console.log(error);
ctx.response.status = 406;
ctx.response.message = "could not parse: "+ error; }},index: async (ctx) => {
// Add your own logic here.
// Send 200 `ok`
ctx.send({
message: 'ok'}); }};Copy the code
The preAnalyzeImportFile method in services/import-content.js performs the operation
'use strict';
const { upload } = require('./utils/oss.js')
/**
* import-content.js service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
*/
module.exports = {
preAnalyzeImportFile: async ctx => {
// Perform the upload operation
const res = await upload(ctx);
returnres; }};Copy the code
The custom plug-in is now complete and included in the Plug-ins menu on the Admin panel. Click to display the plug-in page.
A custom provider
The project uploads files to the strAPI location by default. The project requires uploading to the OSS object store. Strapi provides the strapi-provider-upload-aws- S3 plug-in to upload and obtain files and images on Amazon S3. If you use other methods, you need to change them. The execution process of the research provider can realize storage of any storage type.
Customize the execution process of the provider
The config directory exists in the strapi root directory. Plugins. js in the config directory provides the provider capability (this file is not available by default and needs to be added). The code for provider is as follows:
module.exports = ({ env }) = > ({
// Change the way the upload is created
upload: {
provider: 'test'.providerOptions: {
endPoint: 'string MINIO address'.port: 'number Port number'.useSSL: false.bucketName: 'bucketName', the accessKey: 'accessKey', secretKey: 'secretKey', params: {// parameters provided to provider},},},});Copy the code
The provider is installed as an NPM package through NPM install. Therefore, you need to register an NPM account and publish the provider to the NPM.
The main file of the Provider package is written as follows:
'use strict';
/** * Module dependencies */
/* eslint-disable no-unused-vars */
// Public node modules.
const _ = require('lodash');
const Minio = require('minio');
const fs = require('fs')
const stream = require('stream')
module.exports = {
init(config) {
console.log(config)
const minioClient = newMinio.Client({ ... config, });return {
async upload(file, customParams = {}) {
const { name: fileName, mime: fileMime, size: fileSize, buffer: fileBuffer } = file;
const { endPoint, bucketName, params: { target } } = config;
const bufferStream = new stream.PassThrough();
const readStream = bufferStream.end(fileBuffer);
await minioClient.putObject(config.bucketName, `${target}/${fileName}`, readStream, fileSize);
file.url = `http://${endPoint}/${bucketName}/${target}/${fileName}`}}; }};Copy the code
Json must contain the following configuration to identify the provider
"strapi": {
"isProvider": true
},
Copy the code
Since then, by configuring plugins and custom providers, Minio image uploading and reading are realized and connected to STRAPI content management.
Localization of strapi
Each plug-in in StrAPI has a Translations directory under admin/ SRC or strAPI’s admin/ SRC, which allows for multilingual configuration.
The usage method is as follows:
import { useIntl } from 'react-intl';
const { formatMessage } = useIntl();
const content = formatMessage({ id: 'id' });
Copy the code