summaryrefslogtreecommitdiff
path: root/platform/node/src/node_request.cpp
blob: ea9fc4d7327c2373f6981decdbeb5cca2b899b12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include "node_request.hpp"
#include "node_file_source.hpp"
#include <mbgl/storage/request.hpp>
#include <mbgl/storage/response.hpp>

#include <cmath>
#include <iostream>

namespace node_mbgl {

////////////////////////////////////////////////////////////////////////////////////////////////
// Static Node Methods

v8::Persistent<v8::FunctionTemplate> NodeRequest::constructorTemplate;

void NodeRequest::Init(v8::Handle<v8::Object> target) {
    NanScope();

    v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);
    t->SetClassName(NanNew("Request"));

    NODE_SET_PROTOTYPE_METHOD(t, "respond", Respond);

    NanAssignPersistent(constructorTemplate, t);

    target->Set(NanNew("Request"), t->GetFunction());
}

NAN_METHOD(NodeRequest::New) {
    NanScope();

    // Extract the pointer from the first argument
    if (args.Length() < 2 || !args[0]->IsExternal() || !args[1]->IsExternal()) {
        return NanThrowTypeError("Cannot create Request objects explicitly");
    }

    auto source = reinterpret_cast<NodeFileSource*>(args[0].As<v8::External>()->Value());
    auto resource = reinterpret_cast<mbgl::Resource*>(args[1].As<v8::External>()->Value());
    auto req = new NodeRequest(source, *resource);
    req->Wrap(args.This());

    NanReturnValue(args.This());
}

v8::Handle<v8::Object> NodeRequest::Create(NodeFileSource* source, const mbgl::Resource& resource) {
    NanEscapableScope();

    v8::Local<v8::Value> argv[] = { NanNew<v8::External>(const_cast<NodeFileSource*>(source)),
        NanNew<v8::External>(const_cast<mbgl::Resource*>(&resource)) };
    auto instance = NanNew<v8::FunctionTemplate>(constructorTemplate)->GetFunction()->NewInstance(2, argv);

    instance->ForceSet(NanNew("url"), NanNew(resource.url), v8::ReadOnly);
    instance->ForceSet(NanNew("kind"), NanNew<v8::Integer>(int(resource.kind)), v8::ReadOnly);

    return NanEscapeScope(instance);
}

NAN_METHOD(NodeRequest::Respond) {
    auto nodeRequest = ObjectWrap::Unwrap<NodeRequest>(args.Holder());

    // Request has already been responded to, or was canceled, fail silently.
    if (!nodeRequest->resource) NanReturnUndefined();

    auto source = nodeRequest->source;
    auto resource = std::move(nodeRequest->resource);

    if (args.Length() < 1) {
        return NanThrowTypeError("First argument must be an error object");
    } else if (args[0]->BooleanValue()) {
        auto response = std::make_shared<mbgl::Response>();

        response->status = mbgl::Response::Error;

        // Store the error string.
        const NanUtf8String message { args[0]->ToString() };
        response->message = std::string { *message, size_t(message.length()) };

        source->notify(*resource, response);
    } else if (args.Length() < 2 || !args[1]->IsObject()) {
        return NanThrowTypeError("Second argument must be a response object");
    } else {
        auto response = std::make_shared<mbgl::Response>();
        auto res = args[1]->ToObject();

        response->status = mbgl::Response::Successful;

        if (res->Has(NanNew("modified"))) {
            const double modified = res->Get(NanNew("modified"))->ToNumber()->Value();
            if (!std::isnan(modified)) {
                response->modified = modified / 1000; // JS timestamps are milliseconds
            }
        }

        if (res->Has(NanNew("expires"))) {
            const double expires = res->Get(NanNew("expires"))->ToNumber()->Value();
            if (!std::isnan(expires)) {
                response->expires = expires / 1000; // JS timestamps are milliseconds
            }
        }

        if (res->Has(NanNew("etag"))) {
            auto etagHandle = res->Get(NanNew("etag"));
            if (etagHandle->BooleanValue()) {
                const NanUtf8String etag { etagHandle->ToString() };
                response->etag = std::string { *etag, size_t(etag.length()) };
            }
        }

        if (res->Has(NanNew("data"))) {
            auto dataHandle = res->Get(NanNew("data"));
            if (node::Buffer::HasInstance(dataHandle)) {
                response->data = std::string {
                    node::Buffer::Data(dataHandle),
                    node::Buffer::Length(dataHandle)
                };
            } else {
                return NanThrowTypeError("Response data must be a Buffer");
            }
        }

        // Send the response object to the NodeFileSource object
        source->notify(*resource, response);
    }

    NanReturnUndefined();
}

////////////////////////////////////////////////////////////////////////////////////////////////
// Instance

NodeRequest::NodeRequest(NodeFileSource* source_, const mbgl::Resource& resource_)
    : source(source_),
    resource(std::make_unique<mbgl::Resource>(resource_)) {}

NodeRequest::~NodeRequest() {
}

void NodeRequest::cancel() {
    resource.reset();
}

}