一文學會使用Remix寫API接口
本文提要
Remix 是一個全??蚣?,能寫 api 接口的能肯定是具備的,而且 Remix 雖然定義為全??蚣?,此文章主要探索如何接口。
- Remix 中 api 的書寫方式
- Remix 中 RESTful api 的屬性方式
- 類 MVC 分層接口如何寫 Remix
- 處理上傳示例
接口種類
- 普通 get/post api:即可滿足基本
- RESTful API:有規(guī)范, 需要協同的
- graphql:可控制需要的字段的,良好的跨端
其中如果是一些小項目,沒有必要規(guī)則化的項目,使用 get/post 處理就已經足夠了,如果項目有了很多的人要維護,并且有了一定的規(guī)模,為了方便管理,可以使用 RESTful API 的方式處理。graphql API 手動能力最強。
RESTful API 特點
- 創(chuàng)建:POST /api/resources
- 讀?。篏ET /api/resources/:id
- 更新:PUT /api/resources/:id
- 刪除:DELETE /api/resources/:id
其中,:id 表示資源的唯一標識符。
Remix 中如何處理 api 特點
- loader 處理 get 請求
- action 處理非 get 請求
Loader 函數處理 Get 請求
export const loader = () => { return json({ get: 'loader get' }) }
action 處理非 GET 方法
import { json } from "@remix-run/node"; const handleNotGetRequest = function ({ request }) { const method = request.method; switch (method) { case "POST": return json({ code: 0, method: "POST", message: "添加成功" }); case "PUT": return json({ ok: true, code: 1, method: "PUT", message: "修改成功" }); case "DELETE": return json({ ok: true, code: 1, method: "PUT", message: "刪除成功" }); default: break; } }; // 非 get export const action = ({ request }) => { return handleNotGetRequest({ request }); }; // get export const loader = ({ request }) => { return json({ a: 1, }); };
添加控制層和服務層
為了代碼更加好維護,有結構的代碼時必要的,代碼分層占據重要位置。
如果使用 mongoose
等會定義模型層,定義操作數據的模型,然后使用控制層來操作模型層。構成一個簡單類 MVC 分層結構。當然 Remix 是一個基于 React + Node.js 全??蚣埽褂媚P蛯?服務層:
使用 mongoose 定義模型層, category.model.ts
import mongoose from 'mongoose' const CategorySchema = new mongoose.Schema({ name: String, description: String, createdAt: Date, articleIds: [String] }) export default mongoose.models.Category || mongoose.model('Category', CategorySchema)
使用 category.service.ts
定義服務層,提供給 Remix loader 和 action 操作數據使用
// model import Category from '~/models/category.model' export const delCategoryById = async (_id: string) => { return await Category.remove({ _id }) } export const findCategoryByName = async (name: string) => { return await Category.findOne({ name }) } export const updateCategoryById = async (_id: string, update: any) => { return await Category.findByIdAndUpdate({ _id }, update) } export const findCategoryById = async (_id: string) => { return await Category.findOne({ _id }) } export const addCategoryByName = async (name: string) => { const CategoryEntify = new Category({ name, createdAt: new Date() }) return await CategoryEntify.save() }
暴露 loader 接口
// core import { json } from '@remix-run/node' // service import * as categoryService from '~/services/category.service' // remix loader export async function loader() { const list = await categoryService .getCategoryList({}, '_id createdAt name articleIds', 0, 100000) .then((list) => list) return json({ code: 0, message: 'success', data: { list } }, 200) }
在 loader 函數中通過 services 層來獲取數據,然后使用 json 函數返回數據。
使用 action 方法處理文件上傳接口
api.upload.files.tsx
上傳文件到本地
import type { ActionArgs } from '@remix-run/node' import { json, unstable_composeUploadHandlers as composeUploadHandlers, unstable_createFileUploadHandler as createFileUploadHandler, unstable_createMemoryUploadHandler as createMemoryUploadHandler, unstable_parseMultipartFormData as parseMultipartFormData } from '@remix-run/node' // single file upload export const action = async ({ request }: ActionArgs) => { const uploadHandler = composeUploadHandlers( createFileUploadHandler({ directory: 'public/uploads', // 指定上傳目錄 maxPartSize: 30000000, // 指定大小 file: (file) => { return file.filename } }), createMemoryUploadHandler() ) const formData = await parseMultipartFormData(request, uploadHandler) return json({ imgSrc: formData.get('file') }) // 返回文件名 }
上傳使用 post 方法,在 action 函數使用表單方式進行處理。
小結
本文主要關注點是與 Node.js 其他的框架有什么不同。loader 處理 get 方法,action 處理非 get 請求。從普通的請求處理到處理分層的過程,寫好一個 api 的學習變化過程。
更多關于Remix API接口的資料請關注腳本之家其它相關文章!
相關文章
React router動態(tài)加載組件之適配器模式的應用詳解
這篇文章主要介紹了React router動態(tài)加載組件之適配器模式的應用 ,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09React中setState/useState的使用方法詳細介紹
這篇文章主要介紹了React中setState/useState的使用方法,useState 和 setState 在React開發(fā)過程中 使用很頻繁,但很多人都停留在簡單的使用階段,并沒有正在了解它們的執(zhí)行機制2023-04-04Yarn安裝項目依賴報error?An?unexpected?error?occurred:?“XXXXX:E
這篇文章主要為大家介紹了Yarn安裝項目依賴報error?An?unexpected?error?occurred:?“XXXXX:ESOCKETTIMEOUT”問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03