changed 6 years ago
Published Linked with GitHub

Strapi基本概念及架構(Strapi介紹-中篇)

來源: https://strapi.io/documentation/3.0.0-beta.x/concepts/concepts.html
前篇(快速入門)
中篇(概念架構介紹)
後篇(部署及設定)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
簡單介紹Strapi的概念與架構


1. Strapi 檔案結構(僅介紹API, config檔案)

API, config,

  • **(其他資料夾)
  • /api
    • **(你的API名稱,ex: restaurant)
      • config
      • controllers
      • models
      • services
  • /config
    • environments

2. Strapi 概略運作流程

st=>start: Request請求
e=>end: Response最終回應!
cond1=>inputoutput: ROUTE(分配)
cond=>condition: have policy?
(有無分配規則?)
sub=>subroutine: Policy(執行規則)
(e.g., isAnthenticated?...)
op=>operation: Controller(控制器)
op2=>operation: Service(執行服務)

st(right)->cond1->cond
cond(no)->op()->op2(right)->e
cond(yes)->sub->op

以 restaurant 資料為例

Request

(此Request介紹為一般的客戶端請求,非原文檔中的Request)
來自客戶端的請求
發送請求給Route端處理

Url: http://localhost:1337/restaurants Method: GET //axios 取得所有restaurants的資料 axios({ url: http://localhost:1337/restaurants, method: 'GET', }) .then(res => { console.log(res.response.data); }) .catch(err => { console.log('An error occurred:', err.response); });

Route(包含分配方法及policies)

原文連結

取得請求後,依照各API的routes.json檔案去做請求的分配,分配給controller處理

  • 檔案路徑- ./api/restaurant/config/routes.json
{ "routes": [ { "method": "GET", "path": "/restaurants", "handler": "Restaurant.find", //controller的方法 "config": { "policies": [ //如沒有則不處理policy "global.isAuthenticated" ] } } ] }

Controller

原文連結

從Route中的 handler 取得的方法來做任務執行(類似redux 的 action),將執行services中的方法

  • 以下為strapi的原本方法的原始碼
  • 檔案路徑(自訂方法會直接覆蓋原有方法)- ./api/restaurant/controllers/Restaurants.js

find

module.exports = { /** * Retrieve records. * * @return {Array} */ //可自訂使用的service方法 find(ctx) { if (ctx.query._q) { //將執行product中的service的search方法 return strapi.services.restaurant.search(ctx.query); } return strapi.services.restaurant.find(ctx.query); //也可以不往service,直接丟出資料 //return 'Hi' }, };

Service

原文連結

取得來自controller的方法呼叫,執行對應的service方法

  • 檔案路徑(自訂方法會直接覆蓋原有方法)- ./api/restaurant/services/Restaurants.js

find

module.exports = { /** * Promise to fetch all records * * @return {Promise} */ find(params, populate) { return strapi.query(Restaurant).find(params, populate); }, };

Response

原文連結(response原始資料)

取得service或是controller的資料
e.g., 取得find的資料(API取得的資料)

find

//API拿到的資料 [{"id":1,"restaurant":"Strapi Restaurant","description":"Strapi restaurant is a cosy restaurant delivering one of the very fastest and nicest dining experiences in the world, combining nods to tradition with fierce modernity, warmth with daring.","created_at":"2019-07-31T03:41:56.793Z","updated_at":"2019-07-31T03:44:09.395Z","categories":[{"id":1,"category":"Convenient","created_at":"2019-07-31T03:42:15.241Z","updated_at":"2019-07-31T07:17:32.389Z"},{"id":2,"category":"Time Saving","created_at":"2019-07-31T03:43:25.358Z","updated_at":"2019-07-31T03:43:25.364Z"}]}]

3. Model 資料模型

原文連結

簡單來說,就是在strapi快速入門中,用新增欄位功能產生的資料模型
而我們可以直接使用指令或是修改檔案的方式,來直接新增或是修改欄位!

在新建一個API之後,strapi會自動產生model檔

如果在該API資料夾中無model檔案,可以透過以下CLI指令新建一個
strapi generate:model restaurant name:string

attributes 格式(type)

有以下格式可以使用
string, text, integer, biginteger, float, decimal, password, date, time, datetime, timestamp, boolean, binary, uuid, enumeration, json, email

validations 驗證

有以下驗證可以使用
required (boolean): 是否必須
unique (boolean): 是否唯一
index(boolean): 是否加上索引值(僅適用mongoDB)
max (integer): 最大值(整數)
min (integer): 最小值(整數)

以restaurant為例

路徑- ./api/restaurant/models/Restaurant.settings.json

{ "connection": "default", "collectionName": "restaurants", "info": { "name": "restaurant", //api名稱 "description": "" //api描述 }, "options": { "increments": true, "timestamps": true, "comment": "" ... //選項解釋詳見原文 }, "attributes": { "restaurant": { //restaurant的欄位 "unique": true, //驗證: 唯一 "required": true, //驗證: 必須 "type": "string" //格式: 字串 }, "description": { "type": "text" //格式: 文字 }, "categories": { //此為多個restaurants對多個categories(多對多) "collection": "category", //關聯的欄位(多個的集合) "via": "restaurants" //關聯到自己的欄位(多個) } } }

relations 資料關係

詳細範例以及controller相關使用方法請看這邊

  • One-way 單向
  • One-to-one 一對一
  • One-to-many 一對多
  • Many-to-many 多對多

One-way 單向

資料之間只有單向的連結,例如petowner連結到某位user,而user不會有相應的pet關係

Example:
Path — ./api/pet/models/Pet.settings.json

{ "attributes": { "owner": { "model": "user" } } }

One-to-one 一對一

資料之間為一對一的連結關係,例如user會有一個address,且address也會有一個相應的user欄位

Example:
Path - ./api/user/models/User.settings.json

{ "attributes": { "address": { "model": "address", //連結address "via": "user" } } }

Path - ./api/address/models/Address.settings.json

{ "attributes": { "user": { "model": "user" } } }

One-to-many 一對多(多對一)

資料之間為一對多(多對一)的連結關係,例如user會有很多個articles,且article也會有相應的user(article)欄位

Example:
user
Path - ./api/user/models/User.settings.json

{ "attributes": { "articles": { "collection": "article", "via": "author" } } }

article
Path - ./api/article/models/Article.settings.json

{ "attributes": { "author": { "model": "user" } } }

Many-to-many 多對多

資料之間為多對多的連結關係,例如restaurant會有很多個categories,且category也會有相應的restaurant欄位

Example:
restaurant
Path - ./api/user/models/Restaurant.settings.json

{ "attributes": { "categories": { "collection": "category", "via": "restaurants" } } }

category
Path - ./api/article/models/Category.settings.json

{ "attributes": { "restaurants": { "collection": "restaurant", "via": "categories", "dominant": true } } }

4. 常用CLI(Command Line Interface)指令

strapi new

新建一個strapi專案(常用的為quickstart,即為快速建立專案)
選項:

[--debug|--quickstart|--dbclient=<dbclient> --dbhost=<dbhost> --dbport=<dbport> --dbname=<dbname> --dbusername=<dbusername> --dbpassword=<dbpassword> --dbssl=<dbssl> --dbauth=<dbauth> --dbforce]

strapi develop|dev

http://localhost:1337 開啟開發模式的strapi頁面
加上 /admin 進入儀表板頁面

strapi start

http://localhost:1337 開啟產品模式的strapi頁面
加上 /admin 進入儀表板頁面

strapi build

將目前的strapi專案程式打包建構為產品版本

strapi generate:<api名稱>

可以在指令後面直接加上欄位相關的設定
例如 - strapi generate:restaurant name:string

會自動建立model, controller 等相關資料夾

strapi install <plugin插件名稱>

將會安裝指定插件
例如 - strapi install graphql 就會安裝graphQL的插件(plugin)

Select a repo