M
M
MbIW2019-10-18 14:32:47
PostgreSQL
MbIW, 2019-10-18 14:32:47

How to connect another typescript application to the application on the node, which is responsible for the database?

this is how it connects in a react application, but how to do this on a node?

import axios from 'axios';

export default class BaseHttpService {
  BASE_URL = 'http://localhost:3000';
  _accessToken = null;

  constructor(routerStore) {
    this.routerStore = routerStore;
  }

  async get(endpoint, options = {}) {
    Object.assign(options, this._getCommonOptions());
    return axios.get(`${this.BASE_URL}/${endpoint}`, options)
      .catch(error => this._handleHttpError(error));
  }

  async post(endpoint, data = {}, options = {}) {
    Object.assign(options, this._getCommonOptions());
    return axios.post(`${this.BASE_URL}/${endpoint}`, data, options)
      .catch(error => this._handleHttpError(error));  
  }

  _handleHttpError(error) {
    const { statusCode } = error.response.data;

    if (statusCode !== 401) {
      throw error;
    } else {
      return this._handle401();
    }
  }

  _handle401() {
    this.routerStore.push('/signin');
  }

  _getCommonOptions() {
    const token = this.loadToken();

    return {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    };
  }

  get accessToken() {
    return this._accessToken ? this._accessToken : this.loadToken();
  }

  saveToken(accessToken) {
    this._accessToken = accessToken;
    return localStorage.setItem('accessToken', accessToken);
  }

  loadToken() {
    const token = localStorage.getItem('accessToken');
    this._accessToken = token;
    return token;
  }

  removeToken() {
    localStorage.removeItem('accessToken');
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Celbine, 2019-10-18
@Celbine

1) Create a server that listens on http/ws port and requests
2) Connect to the database using orm (sequelize/mongoose)
3) Respond to requests that come to you via http/ws

M
MbIW, 2019-10-19
@MbIW

Is this even possible or am I asking some nonsense?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question