从另一个控制器呼叫控制器,并根据响应决定操作

时间:2020-03-19 18:23:09

标签: typescript loopbackjs loopback loopback4

我不知道如何执行以下操作:

我有这条路线:“ localhost:3000 / t-clients / {id} / t-consents”

它的作用:存储图像的路径,该图像也应上传到该路径。数据库中的表如下所示:

Tables

因此,我要在客户端ID上将图片上传到服务器端。我有一个上载图片的控制器,该控制器执行上面显示的路线。我要做的是调用控制器,该控制器将文件上传到处理路由的控制器中。我不知道该怎么做。

这是我刚才谈到的两个控制器:

import {inject} from '@loopback/context';
import {
  post,
  Request,
  requestBody,
  Response,
  RestBindings,
} from '@loopback/rest';
import {FILE_UPLOAD_SERVICE} from '../keys';
import {FileUploadHandler} from '../types';

/**
 * A controller to handle file uploads using multipart/form-data media type
 */
export class FileUploadController {
  /**
   * Constructor
   * @param handler - Inject an express request handler to deal with the request
   */
  constructor(
    @inject(FILE_UPLOAD_SERVICE) private handler: FileUploadHandler,
  ) {}
  @post('/file-upload', {
    responses: {
      200: {
        content: {
          'application/json': {
            schema: {
              type: 'object',
            },
          },
        },
        description: 'Files and fields',
      },
    },
  })
  async fileUpload(
    @requestBody({
      description: 'multipart/form-data for files/fields',
      required: true,
      content: {
        'multipart/form-data': {
          // Skip body parsing
          'x-parser': 'stream',
          schema: {
            type: 'object',
            properties: {
              file: {type: 'string', format: 'binary'},
            },
          },
        },
      },
    })
    request: Request,
    @inject(RestBindings.Http.RESPONSE) response: Response,
  ): Promise<object> {
    return new Promise<object>((resolve, reject) => {
      this.handler(request, response, (err: any) => {
        if (err) {
          reject(err);
        } else {
          resolve(FileUploadController.getFilesAndFields(request));
        }
      });
    });
  }

  /**
   * Get files and fields for the request
   * @param request - Http request
   */
  private static getFilesAndFields(request: Request) {
    const uploadedFiles = request.files;

    const mapper = (f: globalThis.Express.Multer.File) => ({
      fieldname: f.fieldname,
      originalname: f.originalname,
      encoding: f.encoding,
      mimetype: f.mimetype,
      size: f.size,
    });

    let files: object[] = [];
    //If only 1 file
    if (Array.isArray(uploadedFiles)) {
      files = uploadedFiles.map(mapper);
    } else {
      //if more than 1
      for (const filename in uploadedFiles) {
        files.push(...uploadedFiles[filename].map(mapper));
      }
    }
    return {files, fields: request.body};
  }
}

另一个

import {
  Count,
  CountSchema,
  Filter,
  repository,
  Where,
} from '@loopback/repository';
import {
  del,
  get,
  getModelSchemaRef,
  getWhereSchemaFor,
  param,
  patch,
  post,
  requestBody,
} from '@loopback/rest';
import {TClient, TConsent} from '../models';
import {TClientRepository} from '../repositories';

export class TClientTConsentController {
  constructor(
    @repository(TClientRepository)
    protected tClientRepository: TClientRepository,
  ) {}

  @get('/t-clients/{id}/t-consents', {
    responses: {
      '200': {
        description: 'Array of TClient has many TConsent',
        content: {
          'application/json': {
            schema: {type: 'array', items: getModelSchemaRef(TConsent)},
          },
        },
      },
    },
  })
  async find(
    @param.path.number('id') id: number,
    @param.query.object('filter') filter?: Filter<TConsent>,
  ): Promise<TConsent[]> {
    return this.tClientRepository.clicon(id).find(filter);
  }

  @post('/t-clients/{id}/t-consents', {
    responses: {
      '200': {
        description: 'TClient model instance',
        content: {'application/json': {schema: getModelSchemaRef(TConsent)}},
      },
    },
  })
  async create(
    @param.path.number('id') id: typeof TClient.prototype.idClient,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(TConsent, {
            title: 'NewTConsentInTClient',
            exclude: ['idConsent', 'fkClient'],
            //optional: ['fkClient']
          }),
        },
      },
    })
    tConsent: Omit<TConsent, 'idConsent'>,
  ): Promise<TConsent> {
    return this.tClientRepository.clicon(id).create(tConsent);
  }

  @patch('/t-clients/{id}/t-consents', {
    responses: {
      '200': {
        description: 'TClient.TConsent PATCH success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  async patch(
    @param.path.number('id') id: number,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(TConsent, {partial: true}),
        },
      },
    })
    tConsent: Partial<TConsent>,
    @param.query.object('where', getWhereSchemaFor(TConsent))
    where?: Where<TConsent>,
  ): Promise<Count> {
    return this.tClientRepository.clicon(id).patch(tConsent, where);
  }

  @del('/t-clients/{id}/t-consents', {
    responses: {
      '200': {
        description: 'TClient.TConsent DELETE success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  async delete(
    @param.path.number('id') id: number,
    @param.query.object('where', getWhereSchemaFor(TConsent))
    where?: Where<TConsent>,
  ): Promise<Count> {
    return this.tClientRepository.clicon(id).delete(where);
  }
}

所以我的目标是将文件上传到路由,路由接收到一条包含文件的消息,也许还有一些文本,例如文件名,然后控制器存储图片并将“ conPath”设置为文件路径。服务器目录。

感谢您的阅读。我可以提供任何详细信息。

0 个答案:

没有答案