Extending Vue components for services

in nodejs •  7 years ago  (edited)

I have begun rewriting a basic app to handle all of my needs in trading crypto-currencies. I am working in nodejs, wrapping it in Electron + Webpack, with a SPA built on vue + vuex + vue-router + vue-loader. I will not be posting every improvement I make, but rather I will focus on posting interesting snippets or milestones.

On architecture...

I need to be able to process a decent amount of data from multiple exchanges, consolidate the data, and then work off it. Therefore I plan to separate my app into several services, with one service to bring all of the data in, and multiple services that can work off of it. For example, I might have an AlertService that watches for certain criteria, a BotService that automates some trade activity, or a NewsService that processes news events for relevant information.

Originally I had some massive headaches trying to couple these individual services within Vue. My first implementation was more-or-less a SetInterval loop in a Vue component's <script></script> tags. Primarily, I needed to meet two goals:

  • Have a robust way to manage this service
  • Be able to easily add additional services as needed

To meet the former, I will spawn a child process for each service; and to meet the latter, I wanted to create a base component that I could then extend for each service. After several hours playing around with vue, here's the solution I came up with.

BaseService.vue

<template>
</template>

<script>

export default {
  name: 'base-service',
  data() {
    return {
      service: 'base-service',
      service_process: null
    }
  },
  created() {
    var path = require('path');
    var fs = require('fs');
    var child_process = require('child_process');

    const app_root = require('app-root-path');
    const service_root = '/src/services/';

    const service_path = app_root.resolve(path.format({dir: service_root, name: this.$data.service, ext: '.js'}));

    if (fs.existsSync(service_path)) {

      this.$data.service_process = child_process.fork(service_path);

      this.$data.service_process.on('message', (m) => {
        console.log(`${this.$data.service} > parent: `, m);
      });

      this.$data.service_process.send({ hello: 'world' });

    } else {
      console.log(`${service_path} does not exist`);
      console.log(`${this.$data.service} cannot start!`);
    }

  }
}

</script>

<style>
</style>

DataService.vue

<template>
</template>

<script>

import BaseService from './BaseService'

export default {
  name: 'data-service',
  extends: BaseService,
  data() {
    return {
      service: 'data-service'
    }
  }
}
</script>

<style>
</style>
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!