使用Loopback4调用MYSQL存储过程的正确方法

时间:2019-08-06 14:03:08

标签: loopback4

我正在尝试使用Loopback 4(https://loopback.io),调用存储过程并获取返回结果的正确方法是什么?我是否要创建存储库或模型(用于返回的数据)?还是应该在控制器内部做所有事情?

1 个答案:

答案 0 :(得分:0)

为简单起见,我直接从控制器调用mysql存储过程。

import {Request, RestBindings, get, ResponseObject, getModelSchemaRef} from '@loopback/rest';
import {inject} from '@loopback/context';
import {param} from '@loopback/openapi-v3';
import {Product} from '../models';

const mysql = require('mysql');
const db = require('mysql-promise')();
const mysqlCreds = require('../datasources/retaildb.datasource.json');

export class V1Controller {
  private connection: any;

constructor(@inject(RestBindings.Http.REQUEST) private req: Request) {
  db.configure(mysqlCreds, mysql);
  this.connection = db;
}

@get('/search', {
  responses: {
    '200': {
      description: 'Search for Products using keyword(s)',
      content: {
        'application/json': {
          schema: {type: 'array', items: getModelSchemaRef(Product)},
        },
      },
    },
  },
})
async search(@param.query.string('key') key: string): Promise<Product> {
  const sqlStmt = mysql.format('CALL PRODUCTSEARCH(?)', [key]);

  return new Promise<Product>(function(resolve, reject) {
    db.query(sqlStmt, function(err: any, results: any) {
      if (err !== null) return reject(err);
      resolve(results[0]);
    });
  });
}

在此示例中,retaildb.datasource.json只是一个包含mysql连接设置的json文件:

{
  "name": "retaildb",
  "connector": "mysql",
  "url": "",
  "host": "ec2-x-x-xxx-xxx.ap-southeast-1.compute.amazonaws.com",
  "port": 3306,
  "user": "root",
  "password": "mysqlpassword",
  "database": "retail"
}

Product是通常的环回模型文件,对应于mysql中存储过程PRODUCTSEARCH返回的内容:

CREATE DEFINER=`root`@`%` PROCEDURE `ProductSearch`(IN `searchkey` varchar(120))
BEGIN
  SELECT * FROM Product WHERE MATCH(description) AGAINST (searchkey IN NATURAL LANGUAGE MODE);
END