nodejs,postgresql,tyscript,typeorm


开发流程:
1、配置router,定义好路由。
2、通过路由创建相对应的controller,并定义好方法,每个变量对应的类型要与之对应。
3、定义相应的request 可以将接收到的参数进行相对应的处理。
4、从controller调用usecase并将参数传过去。
5、在usecase中,调用相对应的entity,接收返回参数,并根据controller对entity进行转换,或者根据response以及reponses进行转换。
6、在usecase中,如何可以使用createQueryBulider,则可以直接调用repository,并将entity传过去,进行数据库操作。
7、若createQueryBulider不能满足查询等的需要,自可以自己定义查询语句,直接在usecase中进行调用。

routerConfigRation.ts
 		app.use('/v1/pages', bodyParser.json(), new PageRouter().router);
pageRouter.ts
		this
		    .router
		    .post('/',
		      PageController.createPage);
PageController.ts
		async createPage(req: express.Request,
		    res: express.Response,
		    next: express.NextFunction): Promise<void> {
		    
		    const pageData: PageRequest = new PageRequest(req);  
		
		    try {
		      const createPageUseCase: CreatePageUseCase = new CreatePageUseCase();
		      const page: PageModel = await createPageUseCase.execute(pageData);
		      const pageResponse: PageResponse = new PageResponse(page);
		
		      HttpResponse.sendCreated(res, pageResponse);
		    } catch (e) {
		      console.log('Failed to create a page.');
		      console.log(e);
		      if (e instanceof AuthenticationException && e.isUsernameExistsException()) {
		        return HttpResponse.sendBadRequestUserExist(res);
		      }
		      return HttpResponse.sendInternalServerError(res);
		    }
		  }
pageRequest.ts
	import * as express from 'express';

//
// @deprecated
//
class PageRequest {

    pageId: string;

    pageName: string;

    status: number;

    publicStatus: number;

    url: string | undefined;

    previewImg: string | undefined;

    createrId: string;

    categoryIds: string[];

    tags: string[];

    widgets: JSON;

    medias: string[];

    contents: string[];

    cssUrl: string | undefined;

    layout: JSON;

    createAt: Date;

    updateAt: Date;

  constructor(req: express.Request) {
    this.pageId = req.body.pageId;
    this.pageName = req.body.pageName;
    this.status = req.body.status;
    this.publicStatus = req.body.publicStatus;
    this.url = req.body.url;
    this.previewImg = req.body.previewImg;
    this.createrId = req.body.createrId;
    this.categoryIds = this.getTenantCode(req.body.categoryIds);
    this.tags = this.getTenantCode(req.body.tags);
    this.widgets = this.getStringify(req.body.widgets);
    this.medias = this.getTenantCode(req.body.medias);
    this.contents = this.getTenantCode(req.body.contents);
    this.cssUrl = req.body.cssUrl;
    this.layout = this.getStringify(req.body.layout);
    this.createAt = req.body.createAt;
    this.updateAt = req.body.updateAt;
  }

  getTenantCode(str:any): any {
    if(str) {
      var tempStr = JSON.stringify(str);
      var newStr = '{' + tempStr.slice(1, -1) + '}'
      return newStr
    }
    return
  }

  getStringify(obj:any): any {
    if(obj){
      return JSON.stringify(obj)
    }
    return
  }
}

Object.seal(PageRequest);
export default PageRequest;
pageModel.ts
	import PageInfoEntity from '../../data/entity/PageInfoEntity';
	
	class PageModel {
	
	  readonly pageId: string;
	
	  readonly pageName: string;
	
	  readonly status: number;
	
	  readonly publicStatus: number;
	
	  readonly url: string | undefined;
	
	  readonly previewImg: string | undefined;
	
	  readonly createrId: string;
	
	  readonly categoryIds: string[];
	
	  readonly tags: string[];
	
	  readonly widgets: JSON;
	
	  readonly medias: string[];
	
	  readonly contents: string[];
	
	  readonly cssUrl: string | undefined;
	
	  readonly layout: JSON;
	
	  readonly createAt: Date;
	
	  readonly updateAt: Date;
	
	  constructor(pageInfoEntity: PageInfoEntity) {
	    this.pageId = pageInfoEntity.pageId;
	    this.pageName = pageInfoEntity.pageName;
	    this.status = pageInfoEntity.status;
	    this.publicStatus = pageInfoEntity.publicStatus;
	    this.url = pageInfoEntity.url;
	    this.previewImg = pageInfoEntity.previewImg;
	    this.createrId = pageInfoEntity.createrId;
	    this.categoryIds = pageInfoEntity.categoryIds;
	    this.tags = pageInfoEntity.tags;
	    this.widgets = pageInfoEntity.widgets;
	    this.medias = pageInfoEntity.medias;
	    this.contents = pageInfoEntity.contents;
	    this.cssUrl = pageInfoEntity.cssUrl;
	    this.layout = pageInfoEntity.layout;
	    this.createAt = pageInfoEntity.createAt;
	    this.updateAt = pageInfoEntity.updateAt;
	  }
	
	  static mapper(pageInfoEntity: PageInfoEntity): PageModel {
	    return new PageModel(pageInfoEntity);
	  }
	}
	
	Object.seal(PageModel);
	export default PageModel;

pageModels.ts
	import PageInfoEntity from '../../data/entity/PageInfoEntity';
	import PageModel from './PageModel';
	class PageModels {
	
	  private constructor() {
	  }
	
	  static mapper(entities: ReadonlyArray<PageInfoEntity>): PageModel[] {
	    const models: PageModel[] = [];
	
	    entities.forEach((entity: PageInfoEntity) => {
	      const model: PageModel =
	      PageModel.mapper(entity);
	      models.push(model);
	    });
	
	    return models;
	  }
	}
	
	Object.seal(PageModels);
	export default PageModels;

createPageUseCase.ts
import RepositoryFactory from '../../data/repository/helper/RepositoryFactory';
import { getManager } from 'typeorm';
import PageQueryRespository from '../../data/repository/query/PageQueryRespository';
import PageRequest from '../../application/request/PageRequest';
import PageMapper from '../mapper/PageMapper';
import PageModel from '../../domain/model/PageModel';
import NoResultException from '../../data/exception/NoResultException';
import NotFoundException from '../exception/NotFoundException';
import PageInfoEntity from '../../data/entity/PageInfoEntity';
import PageRepository from '../../data/repository/PageRepository';
class CreatePageUseCase {

  async execute(pageData:PageRequest): Promise<PageModel> {

    const pageQueryRespository: PageQueryRespository =
      getManager().getCustomRepository(PageQueryRespository);
      await pageQueryRespository.createPage(pageData);

      const pageRepository: PageRepository =
      RepositoryFactory.getRepository(PageRepository);

      try {
        const pageInfoEntity: PageInfoEntity =
          await
          pageRepository
          .findPageByPageId(pageData.pageId);

        return PageMapper.map(pageInfoEntity);
      } catch (e) {
        if (e instanceof NoResultException) {
          throw new NotFoundException('Not found user.');
        }
        throw e;
      }
  }
}

Object.seal(CreatePageUseCase);
export default CreatePageUseCase;
pageMapper.ts
	import PageInfoEntity from '../../data/entity/PageInfoEntity';
	import PageModel from '../../domain/model/PageModel';
	
	class PageMapper {
	
	  private constructor() {}
	
	  static map(pageInfoEntity: PageInfoEntity): PageModel {
	    return new PageModel(pageInfoEntity);
	  }
	
	  static createMap(pageInfoEntity: PageInfoEntity): PageModel {
	    return new PageModel(pageInfoEntity);
	  }
	
	  static mapFromArray(entities: ReadonlyArray<PageInfoEntity>): ReadonlyArray<PageModel> {
	    const pageList: PageModel[] = [];
	    entities.forEach((entity: PageInfoEntity) => {
	      const page: PageModel = new PageModel(entity);
	      pageList.push(page);
	    });
	    return pageList;
	  }
	}
	
	Object.seal(PageMapper);
	export default PageMapper;

pageQuery.ts
import { EntityManager, EntityRepository } from 'typeorm';
import PageRequest from '../../../application/request/PageRequest'
@EntityRepository()
class PageQueryRepository {

  constructor(private manager: EntityManager) {}

  async createPage(pageData: PageRequest): Promise<void> {
    await
    this
    .manager
    .query(
      `INSERT INTO page (
        page_id,
        page_name,
        status,
        public_status,
        url,
        preview_img,
        creater_id,
        category_ids,
        tags,
        widgets,
        medias,
        contents,
        css_url,
        layout,
        create_at,
        update_at) VALUES (
          $1,$2, $3, $4, $5, $6, $7, $8, $9, $10::json, $11, $12, $13, $14, $15, $16)`,
      [
        pageData.pageId,
        pageData.pageName,
        pageData.status,
        pageData.publicStatus,
        pageData.url,
        pageData.previewImg,
        pageData.createrId,
        pageData.categoryIds,
        pageData.tags,
        pageData.widgets,
        pageData.medias,
        pageData.contents,
        pageData.cssUrl,
        pageData.layout,
        pageData.createAt,
        pageData.updateAt
      ],
    );
    return;
  }

  async updatePage(pageData: PageRequest, pageId:string): Promise<PageRequest> {
    let countParams: number = 2;
    const params: any[] = [pageId];
    let sql1: string = `UPDATE page SET`;
    let sql2: string = `page_id = $1`;
    if (pageData.pageName) {
      sql1 = sql1 + ' page_name = $' + countParams + ',';
      params.push(pageData.pageName);
      countParams = countParams + 1;
    }
    if (pageData.status) {
      sql1 = sql1 + ' status = $' + countParams + ',';
      params.push(pageData.status);
      countParams = countParams + 1;
    }
    if (pageData.publicStatus) {
      sql1 = sql1 + ' public_status = $' + countParams + ',';
      params.push(pageData.publicStatus);
      countParams = countParams + 1;
    }
    if (pageData.url) {
      sql1 = sql1 + ' url = $' + countParams + ',';
      params.push(pageData.url);
      countParams = countParams + 1;
    }
    if (pageData.previewImg) {
      sql1 = sql1 + ' preview_img = $' + countParams + ',';
      params.push(pageData.previewImg);
      countParams = countParams + 1;
    }
    if (pageData.createrId) {
      sql1 = sql1 + ' creater_id = $' + countParams + ',';
      params.push(pageData.createrId);
      countParams = countParams + 1;
    }
    if (pageData.categoryIds) {
      sql1 = sql1 + ' category_ids = $' + countParams + ',';
      params.push(pageData.categoryIds);
      countParams = countParams + 1;
    }
    if (pageData.tags) {
      sql1 = sql1 + ' tags = $' + countParams + ',';
      params.push(pageData.tags);
      countParams = countParams + 1;
    }
    if (pageData.widgets) {
      sql1 = sql1 + ' widgets = $' + countParams + ',';
      params.push(pageData.widgets);
      countParams = countParams + 1;
    }
    if (pageData.medias) {
      sql1 = sql1 + ' medias = $' + countParams + ',';
      params.push(pageData.medias);
      countParams = countParams + 1;
    }
    if (pageData.contents) {
      sql1 = sql1 + ' contents = $' + countParams + ',';
      params.push(pageData.contents);
      countParams = countParams + 1;
    }
    if (pageData.cssUrl) {
      sql1 = sql1 + ' css_url = $' + countParams + ',';
      params.push(pageData.cssUrl);
      countParams = countParams + 1;
    }
    if (pageData.layout) {
      sql1 = sql1 + ' layout = $' + countParams + ',';
      params.push(pageData.layout);
      countParams = countParams + 1;
    }
    if (pageData.createAt) {
      sql1 = sql1 + ' create_at = $' + countParams + ',';
      params.push(pageData.createAt);
      countParams = countParams + 1;
    }
    if (pageData.updateAt) {
      sql1 = sql1 + ' update_at = $' + countParams + ',';
      params.push(pageData.updateAt);
      countParams = countParams + 1;
    }
    sql1 = sql1.slice(0, -1)
    let sql: string = sql1 + ' WHERE ' + sql2;
    return await this.manager.query(sql, params);
  }
}

Object.seal(PageQueryRepository);
export default PageQueryRepository;

PageRepository.ts
	import { EntityRepository, ObjectType } from 'typeorm';
	import NoResultException from '../exception/NoResultException';
	import AbstractOmniRepository from './AbstractOmniRepository';
	import PageInfoEntity from '../entity/PageInfoEntity';
	
	@EntityRepository()
	class PageRepository extends AbstractOmniRepository<PageInfoEntity> {
	
	  private static readonly ALIAS: string = 'page';
	
	  // private static readonly USER_QUIT_FLG: string = '0';
	
	  // private static readonly DELETE_FLAG: string = '0';
	
	  isShopGroupCodeRequired(): boolean {
	    return false;
	  }
	
	  isShopCodeRequired(): boolean {
	    return false;
	  }
	
	  isDeleteFlagRequired(): boolean {
	    return false;
	  }
	
	  getObjectType(): ObjectType<PageInfoEntity> {
	    return PageInfoEntity;
	  }
	
	  getAlias(): string {
	    return PageRepository.ALIAS;
	  }
	
	  // async create(entity: PageInfoEntity): Promise<PageInfoEntity> {
	  //   await
	  //     this
	  //       .createCreateQueryBuilder()
	  //       .values(entity)
	  //       .execute();
	  //   return entity;
	  // }
	
	  async createPage(entity: PageInfoEntity): Promise<PageInfoEntity> {
	    await
	      this
	        .createCreateQueryBuilder()
	        .values(entity)
	        .execute();
	    return entity;
	  }
	
	  async findPageByPageId(pageId: string): Promise<PageInfoEntity> {
	    const entity: PageInfoEntity | undefined = await this
	      .createSelectQueryBuilder()
	      .where('page_id = :pageId ', { pageId })
	      .getOne();
	
	    if (!entity) {
	      throw new NoResultException(PageRepository.ALIAS);
	    }
	
	    return entity;
	  }
	
	  async findPageByurl(url: string): Promise<PageInfoEntity> {
	    const entity: PageInfoEntity | undefined = await this
	      .createSelectQueryBuilder()
	      .where('url = :url ', { url })
	      .getOne();
	
	    if (!entity) {
	      throw new NoResultException(PageRepository.ALIAS);
	    }
	
	    return entity;
	  }
	
	  async findPages(): Promise<ReadonlyArray<PageInfoEntity>> {
	    const entity: ReadonlyArray<PageInfoEntity> = await this
	      .createSelectQueryBuilder()
	      .getMany();
	
	    if (!entity) {
	      throw new NoResultException(PageRepository.ALIAS);
	    }
	
	    return entity;
	  }
	
	  async findPagesByOptions(pageurl: string): Promise<ReadonlyArray<PageInfoEntity>> {
	    const entity: ReadonlyArray<PageInfoEntity> = await this
	      .createSelectQueryBuilder()
	      .andWhere('url = :pageurl ', { pageurl })
	      .getMany();
	    if (!entity) {
	      throw new NoResultException(PageRepository.ALIAS);
	    }
	    console.log(entity)
	    return entity;
	  }
	
	  async deletePageBypageId(pageId: string): Promise<void> {
	    await
	      this
	        .createDeleteQueryBuilder()
	        .andWhere('page_id = :pageId', { pageId })
	        .execute();
	  }
	}
	
	Object.seal(PageRepository);
	export default PageRepository;

转载自:https://blog.csdn.net/zzulisboy/article/details/85262158

You may also like...