Объединение наследования с модулями для NodeJS проекта Tesla API - PullRequest
0 голосов
/ 22 апреля 2020

Я пытаюсь создать простое приложение NodeJS, используя express и модули запросов. В этом случае я пытаюсь реализовать шаблон проектирования стратегии, чтобы очистить различные HTTP-запросы, которые выполняются во всем приложении. Моя идея состоит в том, чтобы иметь Опции класс в качестве базового класса, а затем иметь accessToken, getVehicleID, getVehicleStatus, et c. расширить этот базовый класс, переопределяя только те вещи, которые необходимы для элементов (т. е. различное содержимое тела, добавление в заголовки, изменение метода с 'POST' на 'GET' и т. д. c.). Однако я не уверен, что это правильный путь, так как я довольно плохо знаком с JS, и сейчас получаю сообщение об ошибке «Опции не определены». Любая помощь будет оценена! Хотелось бы иметь более масштабируемый дизайн.

Мой класс Options выглядит следующим образом:


Options = (function() {

  function construct() { 
    var self = this;
    var requestURL = '';
    var requestMethod = '';
    var requestHeaders = {};
    var requestBody = {};
  };
   /**
   * Modify request type (i.e. GET, POST, etc.)
   */
  construct.prototype.modifyRequestMethod = function() {
    throw new Error('You have to implement the method doSomething!');
 }

  /**
   * Modify URL
   */
  construct.prototype.modifyUrl = function() {
    throw new Error('You have to implement the method doSomething!');
 }

 /**
  * Modify the request headers
  */
 construct.prototype.modifyHeaders = function() {
    throw new Error('You have to implement the method doSomething!');
  }

  /**
   * Modify the request body
   */
  construct.prototype.modifyBody = function(){
    throw new Error('You have to implement the method doSomething!');
  }

  construct.prototype.updateOptions = function() {
    modifyRequestMethod();
    modifyUrl();
    modifyHeaders();
    modifyBody()
  }

  construct.prototype.returnOptions = function() {
  return {
    url: this.requestURL,
    method: this.requestMethod,
    json: true,
    headers: this.requestHeaders,
    gzip: true,
    body: this.requestBody 
  };
}

  return construct;  

})();

И один из производных классов (accessToken будет):

accessToken = (function(){

    function construct() {
        console.log("Child");
        Options.apply(this, arguments);
        updateOptions();
        returnOptions();
    }


    construct.prototype.modifyRequestMethod = function() {
        this.requestMethod = 'POST';
 }

    construct.prototype.modifyUrl = function() {
        this.requestURL = 'https://owner-api.teslamotors.com/oauth/token';
 }

    construct.prototype.modifyHeaders = function() {
        this.requestHeaders = {
        "x-tesla-user-agent": "TeslaApp/3.4.4-350/fad4a582e/android/8.1.0",
        "user-agent": "Mozilla/5.0 (Linux; Android 8.1.0; Pixel XL Build/OPM4.171019.021.D1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36",
        "Content-Type": "application/json",
        "charset": "utf-8"
      }
  }

    construct.prototype.modifyBody = function(){
        this.requestBody = {
        "grant_type": 'password',
        "client_id": '81527cff06843c8634fdc09e8ac0abefb46ac849f38fe1e431c2ef2106796384',
        "client_secret": 'c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3',
        "email": 'myEmail',
        "password": 'myPassword'
      };
  }

  return construct;


})();

А потом в главном приложении приложения. js:

const express = require("express");
const app = express();
var path = require("path");
var bodyParser = require("body-parser");
var rp = require('request-promise');
const port = 3000;
var firstRequest = require('./helper/accessToken.js');


app.use(express.static(path.join(__dirname, '/public')));
app.set("view engine", "ejs");

let firstRequest = new accessToken();
var myaccessToken;

app.get("/", async(req, resp) => {

  firstRequest.updateOptions();
  const first_response = await rp(firstRequest.returnOptions());
  myaccessToken = (JSON.parse(JSON.stringify(first_response))).access_token;

});


app.listen(port, () => {console.log('Example app listening on port ${port}!') } )


1 Ответ

0 голосов
/ 22 апреля 2020

Вам нужно экспортировать Options, чтобы вы могли ЗАПРОСИТЬ его в своем новом файле

Например, в Options.js

var Options = ...
module.exports = Options

Затем в accessToken.js или app.js:

var Options = require("./Options.js")
...