nest.js 集成graphql TypeScript by mercurius

所有涉及service、model均要在model注冊(cè)

GraphQL是一種強(qiáng)大的 API 查詢語(yǔ)言妻枕,也是使用現(xiàn)有數(shù)據(jù)完成這些查詢的運(yùn)行時(shí)僻族。這是一種優(yōu)雅的方法,可以解決通常在 REST API 中發(fā)現(xiàn)的許多問(wèn)題屡谐。對(duì)于背景述么,建議閱讀GraphQL 和 REST 之間的比較。GraphQL 與TypeScript相結(jié)合愕掏,可幫助您使用 GraphQL 查詢開發(fā)更好的類型安全性度秘,為您提供端到端的輸入。

Mercurius(帶有@nestjs/mercurius)饵撑。我們?yōu)檫@些經(jīng)過(guò)驗(yàn)證的 GraphQL 包提供官方集成剑梳,以提供一種將 GraphQL 與 Nest 結(jié)合使用的簡(jiǎn)單方法(請(qǐng)在此處查看更多集成)唆貌。

安裝

# graphql 
$ yarn add @nestjs/graphql @nestjs/mercurius graphql mercurius graphql-scalars
# 切換fastify 內(nèi)核
$  yarn add @nestjs/platform-fastify

聲明

  • /src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import configuration from 'config/configuration';
import { SequelizeModule, SequelizeModuleOptions } from '@nestjs/sequelize';
import { DataLogHisModel } from './model/customer/data-log-his.model';
import { DataopOperationModel } from './model/customer/dataop-operation.model';
import { DataopItemOperationModel } from './model/customer/dataop-item-operation.model';
import { OrgRoleModel } from './model/customer/org-role.model';
import { OrganizationModel } from './model/customer/organization.model';
import { OrgroleUserModel } from './model/customer/orgrole-user.model';
import { RoleModel } from './model/customer/role.model';
import { UserModel } from './model/customer/user.model';
import { WebopOrgroleModel } from './model/customer/webop-orgrole.model';
import { WebOperationModel } from './model/customer/web-operation.model';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
import { GraphQLJSONObject } from 'graphql-scalars';
import { MercuriusDriver, MercuriusDriverConfig } from '@nestjs/mercurius';

const envFilePath = ['env/.env'];
if (process.env.NODE_ENV) {
  envFilePath.unshift(`env/.env.${process.env.NODE_ENV}`);
}

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
      envFilePath,
    }),
    SequelizeModule.forRoot({
      ...dbCustomerConfig(),
      models: [
        DataLogHisModel,
        DataopOperationModel,
        DataopItemOperationModel,
        DataopOperationModel,
        OrgRoleModel,
        OrganizationModel,
        OrgroleUserModel,
        RoleModel,
        UserModel,
        WebOperationModel,
        WebopOrgroleModel,
      ],
      logging: (...msg) => console.log(msg),
    } as SequelizeModuleOptions),
    // Mercurius 不支持異步
    GraphQLModule.forRoot<MercuriusDriverConfig>({
      driver: MercuriusDriver,
      graphiql: true,
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
      sortSchema: true,
      resolvers: { JSONObject: GraphQLJSONObject },
      path: `/gql`, // graphql 路徑
      prefix: process.env.PREFIX, // graphiql 前綴
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
function dbCustomerConfig(): SequelizeModuleOptions {
  throw new Error('Function not implemented.');
}

  • /src/main.ts

Mercurius 依賴于 Fastify 切換app內(nèi)核

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );

  const configService = app.get(ConfigService);
  const PORT = configService.get('PORT');
  const HOST = configService.get('HOST');
  const PREFIX = `/${configService.get('PREFIX')}`;
  const PROJECTNAME = configService.get('PROJECTNAME');
  const logger: Logger = new Logger('main.ts');

  await app.listen(PORT, HOST, () => {
    logger.log(
      `[${PROJECTNAME}]已經(jīng)啟動(dòng),接口請(qǐng)?jiān)L問(wèn): 
      http://${HOST}:${PORT}${PREFIX}
      http://${HOST}:${PORT}${PREFIX}/graphiql
      `,
    );
  });
}
bootstrap();

代碼生成

# 選擇 user 對(duì)象 生成
$ yarn code
image.png

基礎(chǔ)對(duì)象代碼

  • /src/utils/common.input
import { Field, InputType, Int } from '@nestjs/graphql';
import { GraphQLJSONObject } from 'graphql-scalars';

/**
 * 查詢用參數(shù)
 */
@InputType()
export class FindAllInput {
  @Field(() => GraphQLJSONObject, {
    nullable: true,
    description: '過(guò)濾條件',
  })
  where?: any;

  @Field(() => [[String]], { nullable: true, description: '排序' })
  orderBy?: Array<Array<string>>;

  @Field(() => Int, { nullable: true })
  limit?: number;

  @Field(() => Int, { nullable: true })
  skip?: number;
}

  • /src/utils/base-service.ts
import { GraphQLJSONObject } from 'graphql-scalars';
import {
  get,
  isArray,
  isFunction,
  isObject,
  mapKeys,
  set,
  startsWith,
  toInteger,
} from 'lodash';
import { Op, WhereOptions } from 'sequelize';
import { JwtAuthEntity } from 'src/auth/jwt-auth-entity';
import { BaseModel } from 'src/model/base.model';
import { FindAllInput } from './common.input';

export type ModelStatic = typeof BaseModel & {
  new (): BaseModel;
};

export type DefaultT = any;

export abstract class IBaseService<T extends BaseModel = DefaultT> {
  abstract get GetModel(): typeof BaseModel;

  /**
   * 獲取列表
   * @param param
   * @returns
   */
  public findAll<X = T>(
    param: FindAllInput,
    user?: JwtAuthEntity,
  ): Promise<Array<X>> {
    const sqOptions = {
      where: this.jsonToWhere(param.where),
      limit: param?.limit || toInteger(process.env.SQ_LIMIT || 1000),
      offset: param?.skip,
      order: param?.orderBy || [['id', 'DESC']],
    };

    return this.GetModel.findAll(sqOptions as any) as any;
  }

  /**
   * 獲取行數(shù)
   * @param param
   * @returns
   */
  public findCount(
    param: typeof GraphQLJSONObject,
    user?: JwtAuthEntity,
  ): Promise<number> {
    return this.GetModel.count({
      where: this.jsonToWhere(param),
    });
  }

  /**
   * 根據(jù)id獲取
   * @param param
   * @returns
   */
  public findByPk<X = T>(param: string, user?: JwtAuthEntity): Promise<X> {
    return this.GetModel.findByPk(param) as any;
  }

  public findOne<X = T>(param: FindAllInput, user?: JwtAuthEntity): Promise<X> {
    const sqOptions = {
      where: this.jsonToWhere(param.where),
      limit: param?.limit || toInteger(process.env.SQ_LIMIT || 1000),
      offset: param?.skip,
      order: param?.orderBy || [['id', 'DESC']],
    };
    return this.GetModel.findOne(sqOptions as any) as any;
  }

  public create<X = T>(
    createInput: X | any,
    user?: JwtAuthEntity,
  ): Promise<X | any> {
    createInput.createdId = user?.userId;
    return this.GetModel.create(createInput as any) as any;
  }

  /**
   *
   * @param id
   * @param updateInput
   * @param user
   * @returns
   */
  public async update<X = T>(
    id: string,
    updateInput: X,
    user?: JwtAuthEntity,
  ): Promise<X> {
    return this.GetModel.findByPk(id).then((res) => {
      mapKeys(updateInput as any, (value, key) => res.set(key, value));
      res.updatedId = user?.userId;
      return res.save();
    }) as any;
  }

  /**
   * 對(duì)象映射
   * @param model
   * @param input
   * @returns
   */
  public mapperModel<X = T>(model: X, input: any) {
    mapKeys(input, (value, key) => {
      const setFun = get(model, 'set');
      if (setFun && isFunction(setFun)) {
        (model as BaseModel).set(key, value);
      } else {
        set(model as any, key, value);
      }
    });
    return model;
  }

  /**
   * 邏輯刪除
   * @param id
   * @returns
   */
  public async remove(id: string, user?: JwtAuthEntity): Promise<string> {
    return this.GetModel.findByPk(id)
      .then((res) => {
        res.deletedId = user?.userId;
        return res.destroy();
      })
      .then(() => {
        return id;
      })
      .catch((error) => {
        throw error;
      });
  }

  /**
   * 刪除
   * @param id
   * @param user
   * @returns
   */
  public async distory(id: string, user?: JwtAuthEntity): Promise<string> {
    return this.GetModel.findByPk(id)
      .then((res) => {
        res.deletedId = user?.userId;
        return res.destroy();
      })
      .then(() => {
        return id;
      })
      .catch((error) => {
        throw error;
      });
  }

  /**
   * json 查詢參數(shù) 轉(zhuǎn)換為 sequelize where條件
   * @param param
   * @returns
   */
  public jsonToWhere(param: any): WhereOptions {
    if (!param || !isObject(param)) {
      return param;
    }
    return this.setOp(param);
  }

  /**
   * 屬性迭代 自循環(huán)
   * @param param
   * @returns
   */
  private setOp(param: any) {
    const res = isArray(param) ? [] : {};
    for (const k of Reflect.ownKeys(param)) {
      const v = param[k];
      if (typeof k === 'string') {
        res[startsWith(k, '_') ? Op[k.substring(1, k.length)] : k] =
          isObject(v) && !(v instanceof Date) ? this.setOp(v) : v;
      } else {
        res[k] = isObject(v) && !(v instanceof Date) ? this.setOp(v) : v;
      }
    }
    return res;
  }
}

utils輔助

  • /src/utils/base-entity.ts
import { Field, GraphQLISODateTime, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class BaseEntity {
  @Field(() => String, { description: 'id', nullable: true })
  id: string;

  @Field(() => GraphQLISODateTime, { description: '創(chuàng)建時(shí)間', nullable: true })
  createdAt: Date;

  @Field(() => GraphQLISODateTime, { description: '修改時(shí)間', nullable: true })
  updatedAt: Date;

  @Field(() => GraphQLISODateTime, { description: '刪除時(shí)間', nullable: true })
  deletedAt: Date;

  @Field(() => String, { description: '創(chuàng)建人id', nullable: true })
  createdId: string;

  @Field(() => String, { description: '修改人id', nullable: true })
  updatedId: string;

  @Field(() => String, { description: '刪除人id', nullable: true })
  deletedId: string;

  @Field(() => String, { description: '錯(cuò)誤信息', nullable: true })
  errorMessage?: string;
}

缺少的auth 相關(guān)處理 請(qǐng)參見下一章

nest.js 集成 auth 鑒權(quán)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市垢乙,隨后出現(xiàn)的幾起案子锨咙,更是在濱河造成了極大的恐慌,老刑警劉巖追逮,帶你破解...
    沈念sama閱讀 222,104評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酪刀,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡羊壹,警方通過(guò)查閱死者的電腦和手機(jī)蓖宦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)油猫,“玉大人稠茂,你說(shuō)我怎么就攤上這事∏檠” “怎么了睬关?”我有些...
    開封第一講書人閱讀 168,697評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)毡证。 經(jīng)常有香客問(wèn)我电爹,道長(zhǎng),這世上最難降的妖魔是什么料睛? 我笑而不...
    開封第一講書人閱讀 59,836評(píng)論 1 298
  • 正文 為了忘掉前任丐箩,我火速辦了婚禮,結(jié)果婚禮上恤煞,老公的妹妹穿的比我還像新娘屎勘。我一直安慰自己,他們只是感情好居扒,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評(píng)論 6 397
  • 文/花漫 我一把揭開白布概漱。 她就那樣靜靜地躺著,像睡著了一般喜喂。 火紅的嫁衣襯著肌膚如雪瓤摧。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,441評(píng)論 1 310
  • 那天玉吁,我揣著相機(jī)與錄音照弥,去河邊找鬼。 笑死进副,一個(gè)胖子當(dāng)著我的面吹牛产喉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,992評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼曾沈,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了鸥昏?” 一聲冷哼從身側(cè)響起塞俱,我...
    開封第一講書人閱讀 39,899評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎吏垮,沒(méi)想到半個(gè)月后障涯,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,457評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡膳汪,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評(píng)論 3 341
  • 正文 我和宋清朗相戀三年唯蝶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片遗嗽。...
    茶點(diǎn)故事閱讀 40,664評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡粘我,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出痹换,到底是詐尸還是另有隱情征字,我是刑警寧澤,帶...
    沈念sama閱讀 36,346評(píng)論 5 350
  • 正文 年R本政府宣布娇豫,位于F島的核電站匙姜,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏冯痢。R本人自食惡果不足惜氮昧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評(píng)論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望浦楣。 院中可真熱鬧袖肥,春花似錦、人聲如沸椒振。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)澎迎。三九已至庐杨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間夹供,已是汗流浹背灵份。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留哮洽,地道東北人填渠。 一個(gè)月前我還...
    沈念sama閱讀 49,081評(píng)論 3 377
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親氛什。 傳聞我的和親對(duì)象是個(gè)殘疾皇子莺葫,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容