NextJS 服务器操作类?

问题描述 投票:0回答:1

我喜欢以 OOP 方式构建服务,并通过类来保持相关的交互。

我希望将我的整个类及其方法用作服务器操作,以便在 NextJS 应用程序中与我的数据库进行交互。

关于如何完成此操作的任何想法,或者“使用服务器”指令是否涵盖了文件?


import { CollectionService } from "./collectionsService";

export interface resumeType {
  id?: string;
  image_url: string;
  download: string;
  view: string;
  categories: string[];
}

class resumeCollectionService extends CollectionService<resumeType> {
  constructor() {
    super('resumes');
  }
}
next.js react-server-components server-action
1个回答
0
投票

不幸的是,服务器操作只能是异步自由函数(不是类或类中的函数)。并且参数和返回值必须是可序列化的。

但是你可以将其视为服务器的入口点,在其中构建自己的服务对象,之后的所有内容仍然可以是 OOP。

// ./actions.ts
"use server";

export async function getResumesAction() {
  // Construct your service, or use some sort of dependency injection to get your service.
  const resumeService = new resumeCollectionService();
  return resumeService.getResumes();
}

您可以直接在客户端调用

getResumesAction()
,但如果您想以更OOP的方式进行操作,也可以将所有相关逻辑封装在一个类中,并在类内部调用服务器操作。

import { getResumesAction } from "./actions";

export class resumeCollectionClientService {
  async getResumes() {
    // ... Maybe do something here.
    
    return await getResumesAction();
  }

  async uploadResume(resume: any) { /* ... */ }
}
© www.soinside.com 2019 - 2024. All rights reserved.