1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef GIN_DATA_OBJECT_BUILDER_H_
6 #define GIN_DATA_OBJECT_BUILDER_H_
10 #include "base/check.h"
11 #include "base/memory/raw_ptr.h"
12 #include "base/strings/string_piece.h"
13 #include "gin/converter.h"
14 #include "gin/gin_export.h"
15 #include "v8/include/v8-forward.h"
16 #include "v8/include/v8-object.h"
20 // Constructs a JavaScript object with a series of data properties.
21 // (As with default data properties in JavaScript, these properties are
22 // configurable, writable and enumerable.)
24 // Values are automatically converted using gin::Converter, though if
25 // using a type where the conversion may fail, callers must convert ahead of
28 // This class avoids the pitfall of using v8::Object::Set, which may invoke
29 // setters on the object prototype.
32 // v8::Local<v8::Object> object = gin::DataObjectBuilder(isolate)
33 // .Set("boolean", true)
34 // .Set("integer", 42)
37 // Because this builder class contains local handles, callers must ensure it
38 // does not outlive the scope in which it is created.
39 class GIN_EXPORT DataObjectBuilder {
41 explicit DataObjectBuilder(v8::Isolate* isolate);
42 DataObjectBuilder(const DataObjectBuilder&) = delete;
43 DataObjectBuilder& operator=(const DataObjectBuilder&) = delete;
48 DataObjectBuilder& Set(base::StringPiece key, T&& value) {
49 DCHECK(!object_.IsEmpty());
50 v8::Local<v8::String> v8_key = StringToSymbol(isolate_, key);
51 v8::Local<v8::Value> v8_value =
52 ConvertToV8(isolate_, std::forward<T>(value));
53 CHECK(object_->CreateDataProperty(context_, v8_key, v8_value).ToChecked());
58 DataObjectBuilder& Set(uint32_t index, T&& value) {
59 DCHECK(!object_.IsEmpty());
60 v8::Local<v8::Value> v8_value =
61 ConvertToV8(isolate_, std::forward<T>(value));
62 CHECK(object_->CreateDataProperty(context_, index, v8_value).ToChecked());
66 v8::Local<v8::Object> Build() {
67 DCHECK(!object_.IsEmpty());
68 v8::Local<v8::Object> result = object_;
74 raw_ptr<v8::Isolate> isolate_;
75 v8::Local<v8::Context> context_;
76 v8::Local<v8::Object> object_;
81 #endif // GIN_DATA_OBJECT_BUILDER_H_