NestJS로 빠르고 맞춤설정 가능한 관리자 패널을 구축하세요.

18306 단어 crudreactrefinenestjs
설명된 모든 단계는 이 문서repo에 있습니다.

소개



NestJS은 효율적이고 확장 가능한 Node.js 서버측 애플리케이션을 구축하기 위한 프레임워크입니다. nestjsx/crud을 사용하면 이 프레임워크에 CRUD 기능을 빠르고 쉽게 추가할 수 있습니다.

이 기사에서는 간단한 job-posting 응용 프로그램을 준비합니다. 또한 관리자 패널에 refine 프레임워크를 사용합니다. 프로젝트는 api와 admin의 두 부분으로 구성됩니다.

NestJS 나머지 API



NestJS를 사용하려면 노드(>= 10.13.0, v13 제외) 및 npm이 설치되어 있어야 합니다.

프로젝트 폴더 생성

mkdir job-posting-app
cd job-posting-app


Nest CLI 을 사용하면 새 프로젝트를 설정하는 것이 매우 간단합니다. npm이 설치된 상태에서 OS 터미널에서 다음 명령을 사용하여 새 Nest 프로젝트를 만들 수 있습니다.

npm i -g @nestjs/cli
nest new api


TypeORM은 확실히 node.js 세계에서 사용 가능한 가장 성숙한 ORM입니다. TypeScript로 작성되었기 때문에 Nest 프레임워크와 꽤 잘 작동합니다. 저는 데이터베이스로 mysql을 선택했습니다. TypeORM은 많은 데이터베이스(MySQL, MariaDB, Postgres 등)를 지원합니다.

이 라이브러리를 시작하려면 필요한 모든 종속성을 설치해야 합니다.

npm install --save @nestjs/typeorm @nestjs/config typeorm mysql2


  • .env.example 파일을 만듭니다. 여기에 데이터베이스 정보를 저장합니다.
  • MySQL용 파일docker-compose을 만들고 구성합니다.
  • 마이그레이션을 위한 ormconfig.ts 파일을 만듭니다.
  • 마이그레이션을 위해 package.json 파일에 다음 스크립트를 추가합니다.

  • "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js",
    "db:migration:generate": "npm run typeorm -- migration:generate",
    "db:migration:run": "npm run typeorm -- migration:run",
    "db:migration:revert": "npm run typeorm -- migration:revert",
    "db:refresh": "npm run typeorm schema:drop && npm run db:migration:run"
    


  • TypeOrmModuleapp.module.ts로 가져오기

  • nestjsx-crud 설치
    nestjsx-crud 라이브러리는 crud 기능을 더 쉽게 만들어주기 때문에 사용했습니다.

    npm i @nestjsx/crud @nestjsx/crud-typeorm class-transformer class-validator
    


    Entity Contorllers 및 서비스를 생성하는 단계가 매우 길기 때문에 단계별로 설명하지 않습니다. 자세한 내용은 repo에서 확인하실 수 있습니다.

    nestjsx/crud를 사용하여 이러한 끝점을 자동으로 생성했습니다.



    이제 관리자 패널을 수정해 보겠습니다. Superplate 을 사용하여 refine 프로젝트를 빠르게 생성할 수 있습니다.

    npx superplate-cli admin
    


    아래와 같이 대답하십시오.

    ✔ Select your project type › refine
    ✔ What will be the name of your app · admin
    ✔ Do you want to customize theme?: · less
    ✔ Data Provider: · nestjsx-crud-data-provider
    ✔ Auth Provider: · none
    ✔ Do you want to add an example page? · example-resource
    ✔ Do you want to customize layout? · custom-layout
    ✔ i18n - Internationalization: · no
    



    cd admin
    npm run dev
    


    Refine의 샘플 애플리케이션이 여러분을 환영할 것입니다.



    admin/src/App.tsx에서 API URL 변경

    const API_URL = "http://localhost:3000";
    

    companies crud 끝점에 대한 구체화에 목록 페이지를 추가해 보겠습니다.

    /admin/src/pages/companies/list.tsx

    import {
      List,
      Table,
      TextField,
      useTable,
      IResourceComponentsProps,
      getDefaultSortOrder,
      Space,
      EditButton,
      DeleteButton,
      TagField,
      ShowButton,
    } from "@pankod/refine";
    import { ICompany } from "interfaces";
    
    export const CompanyList: React.FC<IResourceComponentsProps> = () => {
      const { tableProps, sorter } = useTable<ICompany>({
        initialSorter: [
          {
            field: "id",
            order: "desc",
          },
        ],
      });
    
      return (
        <List>
          <Table {...tableProps} rowKey="id">
            <Table.Column
              dataIndex="id"
              key="id"
              title="ID"
              render={(value) => <TextField value={value} />}
              defaultSortOrder={getDefaultSortOrder("id", sorter)}
              sorter
            />
            <Table.Column
              dataIndex="name"
              key="name"
              title="Name"
              render={(value) => <TextField value={value} />}
              defaultSortOrder={getDefaultSortOrder("name", sorter)}
              sorter
            />
            <Table.Column
              dataIndex="location"
              key="location"
              title="Location"
              render={(value) => <TextField value={value} />}
              defaultSortOrder={getDefaultSortOrder("location", sorter)}
              sorter
            />
            <Table.Column
              dataIndex="isActive"
              key="isActive"
              title="Is Active"
              render={(value) => <TagField value={value} />}
              defaultSortOrder={getDefaultSortOrder("status", sorter)}
              sorter
            />
            <Table.Column<ICompany>
              title="Actions"
              dataIndex="actions"
              render={(_, record) => (
                <Space>
                  <EditButton hideText size="small" recordItemId={record.id} />
                  <ShowButton hideText size="small" recordItemId={record.id} />
                  <DeleteButton hideText size="small" recordItemId={record.id} />
                </Space>
              )}
            />
          </Table>
        </List>
      );
    };
    


    마찬가지로 페이지 폴더 아래에 생성, 편집 및 작업 crud 페이지를 추가해 보겠습니다.

    다음으로 <Refine>(App.tsx)의 리소스를 정의해 보겠습니다.

          <Refine
               dataProvider={dataProvider}
               ...
                resources={[
                    {
                       name: "companies",
                       list: CompanyList,
                       create: CompanyCreate,
                       edit: CompanyEdit,
                       show: CompanyShow,
                    },
                    {
                       name: "jobs",
                       list: JobList,
                       create: JobCreate,
                       edit: JobEdit,
                       show: CompanyShow,
                    },
               ]}
        />
    


    좋은 웹페이지 즐겨찾기