breejs / bree

Bree is a Node.js and JavaScript job task scheduler with worker threads, cron, Date, and human syntax. Built for @ladjs, @forwardemail, @spamscanner, @cabinjs.
https://jobscheduler.net
MIT License
2.96k stars 80 forks source link

[discussion] Unexpected token '{' when calling an object.method as function #170

Closed tommasodargenio closed 2 years ago

tommasodargenio commented 2 years ago

Describe the bug

Actual behavior

When calling an object.method as function I get an exception, if I use a normal function instead it works without issues.

Worker for job "test_fetch" online
[worker eval]:1
(status() {
          ^

SyntaxError: Unexpected token '{'
    at new Script (node:vm:100:7)
    at createScript (node:vm:257:10)
    at Object.runInThisContext (node:vm:305:10)
    at node:internal/process/execution:75:19
    at [worker eval]-wrapper:6:22
    at evalScript (node:internal/process/execution:74:60)
    at MessagePort.<anonymous> (node:internal/main/worker_thread:176:7)
    at MessagePort.[nodejs.internal.kHybridDispatch] (node:internal/event_target:647:20)
    at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28)

Expected behavior

I would expect to see the s.status() method to be invoked every 5s, as it would if using a normal function

Code to reproduce

const Cabin = require('cabin');
const scheduler = require('bree');
class testClass {
  status() {
     console.log('test fecth data' + ' ' + Date().toString());
  }
}
const s = new testClass();

let fetch_job = new scheduler({
    root: false,
    logger: new Cabin(),
    jobs: [
    {
        name: 'test_fetch',                                         
        interval: '5s',
        path: s.status
    }
  ]
}); 
fetch_job.start(); 

Checklist

shadowgate15 commented 2 years ago

s.status does not return a callable string. it would return

'status() {\n' +
  "     console.log('test fecth data' + ' ' + Date().toString());\n" +
  '  }'

This is a limitation of Worker Threads and NodeJS so there isn't a lot we can do about it. you would need to define the function outside of a class or use a wrapper function to define and call the class.

The function feature is only provided for simplistic use and really should be avoided as it uses eval which can have security implications.