1 /*********************************************************************
2  * NAN - Native Abstractions for Node.js
3  *
4  * Copyright (c) 2018 NAN contributors
5  *
6  * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
7  ********************************************************************/
8 
9 #include <nan.h>
10 
11 #include "sleep.h"  // NOLINT(build/include)
12 
13 using namespace Nan;  // NOLINT(build/namespaces)
14 
15 // Custom data type: This serves as an example of how external
16 // libraries could be hooked in, populate their objects and send them to JS.
17 struct data_t {
18   int index;
19   int data;
20 };
21 
22 // Unlike test/cpp/ayncprogressworker.cpp this test is explicitly templated.
23 template<typename T>
24 class ProgressWorker : public AsyncProgressWorkerBase<T> {
25  public:
ProgressWorker(Callback * callback,Callback * progress,int milliseconds,int iters)26   ProgressWorker(
27       Callback *callback
28     , Callback *progress
29     , int milliseconds
30     , int iters)
31     : AsyncProgressWorkerBase<T>(callback), progress(progress)
32     , milliseconds(milliseconds), iters(iters) {}
33 
~ProgressWorker()34   ~ProgressWorker() {
35     delete progress;
36   }
37 
Execute(const typename AsyncProgressWorkerBase<T>::ExecutionProgress & progress)38   void Execute (
39     const typename AsyncProgressWorkerBase<T>::ExecutionProgress& progress) {
40     data_t data;
41     for (int i = 0; i < iters; ++i) {
42       data.index = i;
43       data.data = i * 2;
44       progress.Send(&data, 1);
45       Sleep(milliseconds);
46     }
47   }
48 
HandleProgressCallback(const T * data,size_t count)49   void HandleProgressCallback(const T *data, size_t count) {
50     HandleScope scope;
51     v8::Local<v8::Object> obj = Nan::New<v8::Object>();
52     Nan::Set(
53       obj,
54       Nan::New("index").ToLocalChecked(),
55       New<v8::Integer>(data->index));
56     Nan::Set(
57       obj,
58       Nan::New("data").ToLocalChecked(),
59       New<v8::Integer>(data->data));
60 
61     v8::Local<v8::Value> argv[] = { obj };
62     progress->Call(1, argv, this->async_resource);
63   }
64 
65  private:
66   Callback *progress;
67   int milliseconds;
68   int iters;
69 };
70 
NAN_METHOD(DoProgress)71 NAN_METHOD(DoProgress) {
72   Callback *progress = new Callback(To<v8::Function>(info[2]).ToLocalChecked());
73   Callback *callback = new Callback(To<v8::Function>(info[3]).ToLocalChecked());
74   AsyncQueueWorker(new ProgressWorker<data_t>(
75       callback
76     , progress
77     , To<uint32_t>(info[0]).FromJust()
78     , To<uint32_t>(info[1]).FromJust()));
79 }
80 
NAN_MODULE_INIT(Init)81 NAN_MODULE_INIT(Init) {
82   Set(target
83     , New<v8::String>("a").ToLocalChecked()
84     , GetFunction(New<v8::FunctionTemplate>(DoProgress)).ToLocalChecked());
85 }
86 
87 NODE_MODULE(asyncprogressworkerstream, Init)
88