【问题标题】:Return of api rest with node返回 api rest with node
【发布时间】:2021-03-26 01:14:47
【问题描述】:

我正在尝试为 Odoo 生成 rest-api - 带有 Nestjs 和 odoo-xmlrpc 的 ERP。我可以连接到 odoo,但我无法响应 odoo 响应我的服务的值。

这是响应值或错误的 odoo 服务:

import { Injectable, OnModuleInit } from '@nestjs/common';
@Injectable()
export class OdooService  {
    private Odoo = require('odoo-xmlrpc');
    public odoo;
    constructor () {
        this.odoo = new this.Odoo({
            url: 'https:/www.xxxxxxxxx.xxx',
            db: 'xxxx',
            username: 'username',
            password: 'password'
        });
    }

    execute(model: string, funtion: string , params: any[], callback) {
        const odoo = new this.Odoo({
            url: 'https:/www.xxxxxxxxx.xxx',
            db: 'xxxx',
            username: 'username',
            password: 'password'
        });
        odoo.connect(async function (error: any): Promise<any> {
            if (error) {
                console.log(error); 
                return [{}];
            }
            odoo.execute_kw(model, funtion, params, function (error: any, values: []) {
               if (error) { 
                   console.log('error :>> ', error);
                   return [{}];
               }
               callback(values);
            })

        })
    }
}

这是使用 odooServive 的服务

import { Injectable } from '@nestjs/common';
import { OdooService } from '../odoo/odoo.service';
import { CreateCountryDto } from './dto/create-country.dto';
import { UpdateCountryDto } from './dto/update-country.dto';

@Injectable()
export class CountriesService {
  constructor(
    private odooService: OdooService
) {}

  async findAll() {
     return await this.odooService.execute('res.country', 'search_read', [[[]], { fields: ['name'] }], async function (response: []) {
      //  console.log(response);
       return  await response;
     });
  }

}

odoo 文档:https://www.odoo.com/documentation/14.0/webservices/odoo.html 库文档:https://www.npmjs.com/package/odoo-xmlrpc

【问题讨论】:

  • 你混淆了使用回调和承诺的方法。没有显示使用承诺,这会使您的所有 awaitasync 无用。回调中的 return 也不会返回到外部函数。您要么需要重构所有这些以对其进行承诺,要么使用标准回调方法

标签: node.js odoo nestjs xml-rpc


【解决方案1】:

将@charlietfl 的评论详细说明为答案,您可以使用这些代码之一,使用回调或使用异步等待

无承诺,无回调

findAll() {
  return this.odooService.execute('res.country', 'search_read', [[[]], { fields: ['name'] }]);
}

使用回调,无需 Promise

findAll() {
  this.odooService.execute('res.country', 'search_read', [[[]], { fields: ['name'] }], function (response: []) {
    return response;
  });
}

使用承诺

async findAll() {
  const response = await this.odooService.execute('res.country', 'search_read', [[[]], { fields: ['name'] }]);

  return response;  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 2014-06-19
    • 1970-01-01
    • 2020-07-30
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多