Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

consumir odoo ionic #4

Open
osmeld opened this issue Sep 18, 2019 · 0 comments
Open

consumir odoo ionic #4

osmeld opened this issue Sep 18, 2019 · 0 comments

Comments

@osmeld
Copy link

osmeld commented Sep 18, 2019

Buenos dias, estoy trabajando en ionic 5 consumiendo la api de odoo 8 por el protocolo jsonrpc

envio mis solicitudes por un post y obtengo un http failure response for url: https://demo.onreserva.com : unknown 0 cuando pruebo en postman funciona correctamente, aqui esta el codigo de mi servicio codigo:

import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Headers, RequestOptions, Http } from '@angular/http';
import { HTTPOriginal } from '@ionic-native/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';
import { HTTP, HTTPResponse } from '@ionic-native/http/ngx';
import { UtilsService } from './utils.service';
import 'rxjs/add/operator/map';

class Cookies { // cookies doesn't work with Android default browser / Ionic

  private session_id: string = null;

  delete_sessionId() {
      this.session_id = null;
      document.cookie = "session_id=; expires=Wed, 29 Jun 2016 00:00:00 UTC";
  }

  get_sessionId() {
      return document
              .cookie.split("; ")
              .filter(x => { return x.indexOf("session_id") === 0; })
              .map(x => { return x.split("=")[1]; })
              .pop() || this.session_id || "";
  }

  set_sessionId(val: string) {
      document.cookie = `session_id=${val}`;
      this.session_id = val;
  }

}

@Injectable({
providedIn: 'root'
})
export class OdoojsonrpcService {

private odoo_server: string;
private http_auth: string;
private cookies: Cookies;
private uniq_id_counter: number = 0;
private shouldManageSessionId: boolean = false; // try without first
private context: Object = JSON.parse(localStorage.getItem("user_context")) || {"lang": "en_US"};
private headers: HttpHeaders;

private jsonRpcID: number = 0;
private list = "/web/database/list";
private get_list = "/web/database/get_list";
private jsonrpc = "/jsonrpc";

constructor(private http: HTTP, private util: UtilsService, @Inject(HttpClient) private https: HttpClient) {
this.cookies = new Cookies();
this.https = https;
}

private buildRequest(url: string, params: any) {
this.uniq_id_counter += 1;
this.jsonRpcID += 1;
if (this.shouldManageSessionId) {
params.session_id = this.cookies.get_sessionId();
}

this.headers = new HttpHeaders({
    "Content-Type": "application/json",
    //"X-Openerp-Session-Id": this.cookies.get_sessionId(),
    //"Authorization": "Basic " + btoa(`${this.http_auth}`),
    "Accept": "application/json",
    "Access-Control-Allow-Origin": "*"
});
return JSON.stringify({
    jsonrpc: "2.0",
    method: "call",
    //id: 1,
    params: params, // payload
});

}

private handleOdooErrors(response: any) {
if (!response.error) {
return response.result;
}

let error = response.error;
let errorObj = {
    title: "    ",
    message: "",
    fullTrace: error
};

if (error.code === 200 && error.message === "Odoo Server Error" && error.data.name === "werkzeug.exceptions.NotFound") {
    errorObj.title = "page_not_found";
    errorObj.message = "HTTP Error";
} else if ( (error.code === 100 && error.message === "Odoo Session Expired") || // v8
            (error.code === 300 && error.message === "OpenERP WebClient Error" && error.data.debug.match("SessionExpiredException")) // v7
        ) {
            errorObj.title = "session_expired";
           // this.cookies.delete_sessionId();
} else if ( (error.message === "Odoo Server Error" && /FATAL:  database "(.+)" does not exist/.test(error.data.message))) {
    errorObj.title = "database_not_found";
    errorObj.message = error.data.message;
} else if ( (error.data.name === "openerp.exceptions.AccessError")) {
    errorObj.title = "AccessError";
    errorObj.message = error.data.message;
} else {
    let split = ("" + error.data.fault_code).split("\n")[0].split(" -- ");
    if (split.length > 1) {
        error.type = split.shift();
        error.data.fault_code = error.data.fault_code.substr(error.type.length + 4);
    }

    if (error.code === 200 && error.type) {
        errorObj.title = error.type;
        errorObj.message = error.data.fault_code.replace(/\n/g, "<br />");
    } else {
        errorObj.title = error.message;
        errorObj.message = error.data.debug.replace(/\n/g, "<br />");
    }
}
return Promise.reject(errorObj);

}

private handleHttpErrors(error: any) {
return Promise.reject(error.message || error);
}

public sendRequest(url: string, params: Object): Promise {
let body = this.buildRequest(url, params);
/*let options = new RequestOptions({
headers: this.headers
});

this.http.setDataSerializer("json");
//this.http.setSSLCertMode("nocheck");
return new Promise ( (resolve) => {
    this.http.post(this.odoo_server + url, body, options)
  .then((data:HTTPResponse) =>{
    console.log(data.data);
    let response = JSON.parse(data.data)
    resolve(response)
  })
  .catch(error => {
    resolve(error.error)
  }); 
})*/

return this.https.post(this.odoo_server + url, body, {headers: this.headers})
        .toPromise()
        .then(this.handleOdooErrors)
        .catch(this.handleHttpErrors);

}

public init(configs: any) {
this.odoo_server = configs.odoo_server;
this.http_auth = configs.http_auth || null;
}

public setOdooServer(odoo_server: string) {
this.odoo_server = odoo_server;
}

public setHttpAuth(http_auth: string) {
this.http_auth = http_auth;
}

public getServerInfo() {
return this.sendRequest("/web/webclient/version_info", {});
}

public getSessionInfo() {
return this.sendRequest("/web/session/get_session_info", {});
}

public login(db: string, login: string, password: string) {
let params = {
db : db,
login : login,
password : password,
context: {}
};
let $this = this;
return this.sendRequest("/web/session/authenticate", params).then((result: any)=> {
//let res = JSON.stringify(result);
//let response = JSON.parse(res)["result"]
if (!result.uid) {
$this.cookies.delete_sessionId();
return Promise.reject({
title: "wrong_login",
message: "Username and password don't match",
fullTrace: result
});
}
$this.context = result.user_context;
localStorage.setItem("user_context", JSON.stringify($this.context));
$this.cookies.set_sessionId(result.session_id);
return result;
});
}
}

aqui esta la llamada desde mi componente

login(){
console.log(this.db)
console.log(this.email)
console.log(this.password)
console.log(this.util.getCompany())
this.odooRpc.login(this.db, this.email, this.password).then((result:any)=>{
this.presentToast(JSON.stringify(result));
this.navCtrl.navigateForward('/dashboard');
}).catch((error)=>{
this.presentToast(error);
})
}

espero su ayuda llevo varias semanas en este tema probe con http ionic-native y nada

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant