Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Class to be used on controllers

I want to create a Class and make it available on my controllers. I don't want to use helpers in this particular case because I'm planning to create an npm package later with this code. I don't want to create a package now, because I don't want my code to be public.

I've tried adding this code inside a file in the hooks folder:

console.log('Hook executed!');

module.exports = class Test {
    constructor() {
        console.log('Object created!');
    }
}

When I lift the app I see that the hook it's being loaded:

info: Starting app...

Hook executed!

Then in a random controller I'm adding:

const test = new Test();

And when I execute the controller:

ReferenceError: Test is not defined

Update: According to the documentation hooks are defined in a different way. So maybe using hooks is not the best approach. Any ideas on how to make a Class available on the controllers with or without using hooks?

like image 729
fsinisi90 Avatar asked Aug 31 '18 16:08

fsinisi90


1 Answers

Your files should be like these files shown bellow:

myClass.js

'use strict';
class Test {
  constructor() {
    this.name = 'test';
  }
}
module.exports = Test;

The other file which you want to use this class should look like this:

index.js

const Test = require('./myClass');
let a = new Test();
console.log(a.name);

After that when you run index.js file, you will see 'test' in your console.

like image 140
Seyed Ali Akhavani Avatar answered Sep 22 '22 14:09

Seyed Ali Akhavani