AJAX request is cancelled by Chrome when issued from within the extension - javascript

I am doing a simple AJAX request within Chrome extension, but Chrome cancels my request each time. I did specify necessary cross-origin permissions in the manifest file. The server also allows cross-origin requests, i.e I am able to execute my ajax script within a normal browser window. I also tried doing the old way via XMLHttpRequest - the result is the same. What am I missing?
The full JS code loaded by extension is below (getUmsIdByEmail_ is the function):
var AssumeIdentityController = function () {
this.button_ = document.getElementById('button');
this.customer_email_ = document.getElementById('emailfield');
this.addListeners_();
};
AssumeIdentityController.prototype = {
/**
* A cached reference to the button element.
*
* #type {Element}
* #private
*/
button_: null,
/**
* A cached reference to the select element.
*
* #type {Element}
* #private
*/
timeframe_: null,
customer_email_: null,
/**
* Adds event listeners to the button in order to capture a user's click, and
* perform some action in response.
*
* #private
*/
addListeners_: function () {
this.button_.addEventListener('click', this.handleClick_.bind(this));
},
/**
* Given a string, return milliseconds since epoch. If the string isn't
* valid, returns undefined.
*
* #param {string} timeframe One of 'hour', 'day', 'week', '4weeks', or
* 'forever'.
* #returns {number} Milliseconds since epoch.
* #private
*/
getUmsIdByEmail_: function(email){
console.log('attempting to fetch');
var opts = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
fetch('<SERVER_WITH_THE_RESOURCE>', opts).then(function (response) {
return response.json();
})
.then(function (body) {
console.log(body)
});
},
// getTokenByUms_: function(umsId) {
// return token
// }
/**
* Handle a success/failure callback from the `browsingData` API methods,
* updating the UI appropriately.
*
* #private
*/
handleCallback_: function () {
var success = document.createElement('div');
success.classList.add('overlay');
success.setAttribute('role', 'alert');
success.textContent = 'Data has been cleared.';
document.body.appendChild(success);
setTimeout(function() { success.classList.add('visible'); }, 10);
setTimeout(function() {
if (close === false)
success.classList.remove('visible');
else
window.close();
}, 4000);
},
/**
* When a user clicks the button, this method is called: it reads the current
* state of `timeframe_` in order to pull a timeframe, then calls the clearing
* method with appropriate arguments.
*
* #private
*/
handleClick_: function () {
this.getUmsIdByEmail_('sd');
if (this.customer_email_ !== undefined)
{
// var token = getTokenByUms(umsId);
// if(replacePreprodToken(token))
// {
// print('successfully logged in. Refreshing the page');
// }
// else
// {
// print('Can't log in. Please try again later');
// }
}
// }
}
};
document.addEventListener('DOMContentLoaded', function () {
console.log('dom content loaded');
window.PC = new AssumeIdentityController();
});
Permissions in manifest look like this:
...
"permissions": [
"browsingData","declarativeContent","storage","https://*/","http://*/"
],
...

Related

grpc: protobuf cross-language code generation results in naming inconsistency

I found that using snake_case in protobuf definition will have slightly different generated method/class names across different languages. The difference is in the casing if the protocol field name uses snake_case.
Example
A regular protoc code-generation based on the following protocol
syntax = "proto3";
package myservice;
service Myservice {
rpc MyService(Request) returns (Reply) {}
}
message Request {
bool my_foo = 1;
bool my_bar = 2;
}
message Reply {
bool is_succeeded = 1;
}
yields the following generated naming
Python
python -m grpc_tools.protoc -I="${SRC_DIR}" --python_out="${DST_DIR}" --grpc_python_out=$DST_DIR --proto_path="${SRC_DIR}" my.proto
my_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import my_pb2 as my__pb2
class MyserviceStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.MyService = channel.unary_unary(
'/myservice.Myservice/MyService',
request_serializer=my__pb2.Request.SerializeToString,
response_deserializer=my__pb2.Reply.FromString,
)
class MyserviceServicer(object):
"""Missing associated documentation comment in .proto file."""
def MyService(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_MyserviceServicer_to_server(servicer, server):
rpc_method_handlers = {
'MyService': grpc.unary_unary_rpc_method_handler(
servicer.MyService,
request_deserializer=my__pb2.Request.FromString,
response_serializer=my__pb2.Reply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'myservice.Myservice', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class Myservice(object):
"""Missing associated documentation comment in .proto file."""
#staticmethod
def MyService(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/myservice.Myservice/MyService',
my__pb2.Request.SerializeToString,
my__pb2.Reply.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
my_pb2.py
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: my.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# ##protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='my.proto',
package='myservice',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x08my.proto\x12\tmyservice\")\n\x07Request\x12\x0e\n\x06my_foo\x18\x01 \x01(\x08\x12\x0e\n\x06my_bar\x18\x02 \x01(\x08\"\x1d\n\x05Reply\x12\x14\n\x0cis_succeeded\x18\x01 \x01(\x08\x32#\n\tMyservice\x12\x33\n\tMyService\x12\x12.myservice.Request\x1a\x10.myservice.Reply\"\x00\x62\x06proto3'
)
_REQUEST = _descriptor.Descriptor(
name='Request',
full_name='myservice.Request',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='my_foo', full_name='myservice.Request.my_foo', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='my_bar', full_name='myservice.Request.my_bar', index=1,
number=2, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=23,
serialized_end=64,
)
_REPLY = _descriptor.Descriptor(
name='Reply',
full_name='myservice.Reply',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='is_succeeded', full_name='myservice.Reply.is_succeeded', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=66,
serialized_end=95,
)
DESCRIPTOR.message_types_by_name['Request'] = _REQUEST
DESCRIPTOR.message_types_by_name['Reply'] = _REPLY
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Request = _reflection.GeneratedProtocolMessageType('Request', (_message.Message,), {
'DESCRIPTOR' : _REQUEST,
'__module__' : 'my_pb2'
# ##protoc_insertion_point(class_scope:myservice.Request)
})
_sym_db.RegisterMessage(Request)
Reply = _reflection.GeneratedProtocolMessageType('Reply', (_message.Message,), {
'DESCRIPTOR' : _REPLY,
'__module__' : 'my_pb2'
# ##protoc_insertion_point(class_scope:myservice.Reply)
})
_sym_db.RegisterMessage(Reply)
_MYSERVICE = _descriptor.ServiceDescriptor(
name='Myservice',
full_name='myservice.Myservice',
file=DESCRIPTOR,
index=0,
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_start=97,
serialized_end=161,
methods=[
_descriptor.MethodDescriptor(
name='MyService',
full_name='myservice.Myservice.MyService',
index=0,
containing_service=None,
input_type=_REQUEST,
output_type=_REPLY,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
])
_sym_db.RegisterServiceDescriptor(_MYSERVICE)
DESCRIPTOR.services_by_name['Myservice'] = _MYSERVICE
# ##protoc_insertion_point(module_scope)
Node.js
With grpc-node the result looks like this
grpc_tools_node_protoc --js_out=import_style=commonjs,binary:"${DST_DIR}" --grpc_out=grpc_js:"${DST_DIR}" --proto_path="${SRC_DIR}" my.proto
my_grpc_pb.js
// GENERATED CODE -- DO NOT EDIT!
'use strict';
var grpc = require('#grpc/grpc-js');
var my_pb = require('./my_pb.js');
function serialize_myservice_Reply(arg) {
if (!(arg instanceof my_pb.Reply)) {
throw new Error('Expected argument of type myservice.Reply');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_myservice_Reply(buffer_arg) {
return my_pb.Reply.deserializeBinary(new Uint8Array(buffer_arg));
}
function serialize_myservice_Request(arg) {
if (!(arg instanceof my_pb.Request)) {
throw new Error('Expected argument of type myservice.Request');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_myservice_Request(buffer_arg) {
return my_pb.Request.deserializeBinary(new Uint8Array(buffer_arg));
}
var MyserviceService = exports.MyserviceService = {
myService: {
path: '/myservice.Myservice/MyService',
requestStream: false,
responseStream: false,
requestType: my_pb.Request,
responseType: my_pb.Reply,
requestSerialize: serialize_myservice_Request,
requestDeserialize: deserialize_myservice_Request,
responseSerialize: serialize_myservice_Reply,
responseDeserialize: deserialize_myservice_Reply,
},
};
exports.MyserviceClient = grpc.makeGenericClientConstructor(MyserviceService);
my_pb.js
// source: my.proto
/**
* #fileoverview
* #enhanceable
* #suppress {missingRequire} reports error on implicit type usages.
* #suppress {messageConventions} JS Compiler reports an error if a variable or
* field starts with 'MSG_' and isn't a translatable message.
* #public
*/
// GENERATED CODE -- DO NOT EDIT!
/* eslint-disable */
// #ts-nocheck
var jspb = require('google-protobuf');
var goog = jspb;
var global = Function('return this')();
goog.exportSymbol('proto.myservice.Reply', null, global);
goog.exportSymbol('proto.myservice.Request', null, global);
/**
* Generated by JsPbCodeGenerator.
* #param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* #extends {jspb.Message}
* #constructor
*/
proto.myservice.Request = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.myservice.Request, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* #public
* #override
*/
proto.myservice.Request.displayName = 'proto.myservice.Request';
}
/**
* Generated by JsPbCodeGenerator.
* #param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* #extends {jspb.Message}
* #constructor
*/
proto.myservice.Reply = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.myservice.Reply, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* #public
* #override
*/
proto.myservice.Reply.displayName = 'proto.myservice.Reply';
}
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* #param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* #return {!Object}
*/
proto.myservice.Request.prototype.toObject = function(opt_includeInstance) {
return proto.myservice.Request.toObject(opt_includeInstance, this);
};
/**
* Static version of the {#see toObject} method.
* #param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* #param {!proto.myservice.Request} msg The msg instance to transform.
* #return {!Object}
* #suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.myservice.Request.toObject = function(includeInstance, msg) {
var f, obj = {
myFoo: jspb.Message.getBooleanFieldWithDefault(msg, 1, false),
myBar: jspb.Message.getBooleanFieldWithDefault(msg, 2, false)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* #param {jspb.ByteSource} bytes The bytes to deserialize.
* #return {!proto.myservice.Request}
*/
proto.myservice.Request.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.myservice.Request;
return proto.myservice.Request.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* #param {!proto.myservice.Request} msg The message object to deserialize into.
* #param {!jspb.BinaryReader} reader The BinaryReader to use.
* #return {!proto.myservice.Request}
*/
proto.myservice.Request.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = /** #type {boolean} */ (reader.readBool());
msg.setMyFoo(value);
break;
case 2:
var value = /** #type {boolean} */ (reader.readBool());
msg.setMyBar(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* #return {!Uint8Array}
*/
proto.myservice.Request.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.myservice.Request.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* #param {!proto.myservice.Request} message
* #param {!jspb.BinaryWriter} writer
* #suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.myservice.Request.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getMyFoo();
if (f) {
writer.writeBool(
1,
f
);
}
f = message.getMyBar();
if (f) {
writer.writeBool(
2,
f
);
}
};
/**
* optional bool my_foo = 1;
* #return {boolean}
*/
proto.myservice.Request.prototype.getMyFoo = function() {
return /** #type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false));
};
/**
* #param {boolean} value
* #return {!proto.myservice.Request} returns this
*/
proto.myservice.Request.prototype.setMyFoo = function(value) {
return jspb.Message.setProto3BooleanField(this, 1, value);
};
/**
* optional bool my_bar = 2;
* #return {boolean}
*/
proto.myservice.Request.prototype.getMyBar = function() {
return /** #type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false));
};
/**
* #param {boolean} value
* #return {!proto.myservice.Request} returns this
*/
proto.myservice.Request.prototype.setMyBar = function(value) {
return jspb.Message.setProto3BooleanField(this, 2, value);
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* #param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* #return {!Object}
*/
proto.myservice.Reply.prototype.toObject = function(opt_includeInstance) {
return proto.myservice.Reply.toObject(opt_includeInstance, this);
};
/**
* Static version of the {#see toObject} method.
* #param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* #param {!proto.myservice.Reply} msg The msg instance to transform.
* #return {!Object}
* #suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.myservice.Reply.toObject = function(includeInstance, msg) {
var f, obj = {
isSucceeded: jspb.Message.getBooleanFieldWithDefault(msg, 1, false)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* #param {jspb.ByteSource} bytes The bytes to deserialize.
* #return {!proto.myservice.Reply}
*/
proto.myservice.Reply.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.myservice.Reply;
return proto.myservice.Reply.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* #param {!proto.myservice.Reply} msg The message object to deserialize into.
* #param {!jspb.BinaryReader} reader The BinaryReader to use.
* #return {!proto.myservice.Reply}
*/
proto.myservice.Reply.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = /** #type {boolean} */ (reader.readBool());
msg.setIsSucceeded(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* #return {!Uint8Array}
*/
proto.myservice.Reply.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.myservice.Reply.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* #param {!proto.myservice.Reply} message
* #param {!jspb.BinaryWriter} writer
* #suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.myservice.Reply.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getIsSucceeded();
if (f) {
writer.writeBool(
1,
f
);
}
};
/**
* optional bool is_succeeded = 1;
* #return {boolean}
*/
proto.myservice.Reply.prototype.getIsSucceeded = function() {
return /** #type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 1, false));
};
/**
* #param {boolean} value
* #return {!proto.myservice.Reply} returns this
*/
proto.myservice.Reply.prototype.setIsSucceeded = function(value) {
return jspb.Message.setProto3BooleanField(this, 1, value);
};
goog.object.extend(exports, proto.myservice);
Dart
With the same treatment as above
protoc --plugin=protoc-gen-dart="$HOME/.pub-cache/bin/protoc-gen-dart" --dart_out=grpc:"${DST_DIR}" -I"${SRC_DIR}" -I"$IncludeDir" my.proto
my.pbgrpc.dart
///
// Generated code. Do not modify.
// source: my.proto
//
// #dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
import 'dart:async' as $async;
import 'dart:core' as $core;
import 'package:grpc/service_api.dart' as $grpc;
import 'my.pb.dart' as $0;
export 'my.pb.dart';
class MyserviceClient extends $grpc.Client {
static final _$myService = $grpc.ClientMethod<$0.Request, $0.Reply>(
'/myservice.Myservice/MyService',
($0.Request value) => value.writeToBuffer(),
($core.List<$core.int> value) => $0.Reply.fromBuffer(value));
MyserviceClient($grpc.ClientChannel channel,
{$grpc.CallOptions? options,
$core.Iterable<$grpc.ClientInterceptor>? interceptors})
: super(channel, options: options, interceptors: interceptors);
$grpc.ResponseFuture<$0.Reply> myService($0.Request request,
{$grpc.CallOptions? options}) {
return $createUnaryCall(_$myService, request, options: options);
}
}
abstract class MyserviceServiceBase extends $grpc.Service {
$core.String get $name => 'myservice.Myservice';
MyserviceServiceBase() {
$addMethod($grpc.ServiceMethod<$0.Request, $0.Reply>(
'MyService',
myService_Pre,
false,
false,
($core.List<$core.int> value) => $0.Request.fromBuffer(value),
($0.Reply value) => value.writeToBuffer()));
}
$async.Future<$0.Reply> myService_Pre(
$grpc.ServiceCall call, $async.Future<$0.Request> request) async {
return myService(call, await request);
}
$async.Future<$0.Reply> myService($grpc.ServiceCall call, $0.Request request);
}
my.pb.dart
///
// Generated code. Do not modify.
// source: my.proto
//
// #dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
import 'dart:core' as $core;
import 'package:protobuf/protobuf.dart' as $pb;
class Request extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Request', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'myservice'), createEmptyInstance: create)
..aOB(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'myFoo')
..aOB(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'myBar')
..hasRequiredFields = false
;
Request._() : super();
factory Request({
$core.bool? myFoo,
$core.bool? myBar,
}) {
final _result = create();
if (myFoo != null) {
_result.myFoo = myFoo;
}
if (myBar != null) {
_result.myBar = myBar;
}
return _result;
}
factory Request.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
factory Request.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
#$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
Request clone() => Request()..mergeFromMessage(this);
#$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
Request copyWith(void Function(Request) updates) => super.copyWith((message) => updates(message as Request)) as Request; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
#$core.pragma('dart2js:noInline')
static Request create() => Request._();
Request createEmptyInstance() => create();
static $pb.PbList<Request> createRepeated() => $pb.PbList<Request>();
#$core.pragma('dart2js:noInline')
static Request getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Request>(create);
static Request? _defaultInstance;
#$pb.TagNumber(1)
$core.bool get myFoo => $_getBF(0);
#$pb.TagNumber(1)
set myFoo($core.bool v) { $_setBool(0, v); }
#$pb.TagNumber(1)
$core.bool hasMyFoo() => $_has(0);
#$pb.TagNumber(1)
void clearMyFoo() => clearField(1);
#$pb.TagNumber(2)
$core.bool get myBar => $_getBF(1);
#$pb.TagNumber(2)
set myBar($core.bool v) { $_setBool(1, v); }
#$pb.TagNumber(2)
$core.bool hasMyBar() => $_has(1);
#$pb.TagNumber(2)
void clearMyBar() => clearField(2);
}
class Reply extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'Reply', package: const $pb.PackageName(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'myservice'), createEmptyInstance: create)
..aOB(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'isSucceeded')
..hasRequiredFields = false
;
Reply._() : super();
factory Reply({
$core.bool? isSucceeded,
}) {
final _result = create();
if (isSucceeded != null) {
_result.isSucceeded = isSucceeded;
}
return _result;
}
factory Reply.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
factory Reply.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
#$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
Reply clone() => Reply()..mergeFromMessage(this);
#$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
Reply copyWith(void Function(Reply) updates) => super.copyWith((message) => updates(message as Reply)) as Reply; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
#$core.pragma('dart2js:noInline')
static Reply create() => Reply._();
Reply createEmptyInstance() => create();
static $pb.PbList<Reply> createRepeated() => $pb.PbList<Reply>();
#$core.pragma('dart2js:noInline')
static Reply getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Reply>(create);
static Reply? _defaultInstance;
#$pb.TagNumber(1)
$core.bool get isSucceeded => $_getBF(0);
#$pb.TagNumber(1)
set isSucceeded($core.bool v) { $_setBool(0, v); }
#$pb.TagNumber(1)
$core.bool hasIsSucceeded() => $_has(0);
#$pb.TagNumber(1)
void clearIsSucceeded() => clearField(1);
}
Comparison
If we compare the following generated entities
Service class name
Service method name
Request field names
Reply field names
Here are the results
Python
Myservice
MyService
my_foo
my_bar
is_succeeded
Node.js
MyserviceService
myService
accessor: getMyFoo()
accessor: getMyBar()
accessor: getIsSucceeded()
Dart
MyserviceServiceBase
myService
myFoo
myBar
isSucceeded
Question
Although these naming schemes seem to cater to the language-specific convention,
the differences between them caused some maintenance issues.
I wonder if there is a way to ensure an identical casing treatment across all these languages, and possibly all supported languages.
Thanks!
Code generation plugins have complete freedom to generate whatever code they want. Usually, they try to follow the language's conventions. You'd need to have controls for each language, and most won't provide it.
What are the actual maintenance issues that you are facing? Perhaps there is some other way of solving them.

Convert IIFE module to something importable by RollupJS

I am using RollupJS as a bundler, and it can read CommonJS (via a plugin) or ES6 modules. But this module seems to be in UMD format, and I am looking for a quick way I can edit it (without replacing a lot of lines) so that it is in commonJS or ES6 format.
What do folks suggest? I show the top and the bottom of a 5,000 line .js file.
#module vrlinkjs
**/
(function (mak) {
mak.MessageKindEnum = {
Any : -1,
Other : 0,
AttributeUpdate : 1,
Interaction : 2,
Connect : 3,
ObjectDeletion : 4
};
/**
Decodes AttributeUpdate messages into an EnvironmentalStateRepository object.
#class EnvironmentalStateDecoder
#constructor
#augments StateDecoder
#param {WebLVCConnection} webLVCConnection Connection to a WebLVC server
**/
mak.EnvironmentalStateDecoder = function(webLVCConnection) {
mak.StateDecoder.apply(this, arguments);
};
mak.EnvironmentalStateDecoder.prototype = Object.create(mak.StateDecoder.prototype, {
constructor : { value : mak.EnvironmentalStateDecoder },
/**
Decodes a AttributeUpdate message into an EntityStateRepository object.
#method decode
#param {Object} attributeUpdate WebLVC AttributeUpdate message
#param {EntityStateRepository} stateRep State repository to be updated
**/
decode : {
value : function( attributeUpdate, stateRep ) {
// if(this.webLVCConnection.timeStampType == mak.TimeStampType.TimeStampAbsolute &&
// attributeUpdate.TimeStampType == mak.TimeStampType.TimeStampAbsolute) {
// } else {
// stateRep.timeStampType = mak.TimeStampType.TimeStampRelative;
// }
stateRep.timeStampType = mak.TimeStampType.TimeStampRelative;
var curTime = 0.0;
// if (stateRep->timeStampType() == DtTimeStampAbsolute)
// {
// // Use timestamp as time of validity
// curTime = pdu.guessTimeValid(myExConn->clock()->simTime());
// }
// else
// {
// // Use receive time as time of validity
// curTime = myExConn->clock()->simTime();
// }
curTime = this.webLVCConnection.clock.simTime;
if(attributeUpdate.ProcessIdentifier != undefined) {
stateRep.entityIdentifier = attributeUpdate.EntityIdentifier;
}
if(attributeUpdate.Type != undefined) {
stateRep.entityType = attributeUpdate.Type;
}
if(attributeUpdate.ObjectName != undefined) {
stateRep.objectName = attributeUpdate.ObjectName;
}
if(attributeUpdate.GeometryRecords != undefined) {
stateRep.GeometryRecords = attributeUpdate.GeometryRecords;
}
if(attributeUpdate.EnvObjData != undefined) {
if(attributeUpdate.EnvObjData.VrfObjName != undefined) {
stateRep.marking = attributeUpdate.EnvObjData.VrfObjName;
}
}
}
}
});
.....
} (this.mak = this.mak || {}));
UPDATE
I used the ES6 module solution from estus (below), which I really like. It solved the rollup bunding issue, but there is still a runtime error.
But there is a little more that needs to be done. I am getting this error with chrome. I have two varients of the HTML main.html file, one uses the bundle and the other just imports my es6 modules. The error occurs even when I am not using rollup and creating and using the bundle.
Uncaught TypeError: Cannot set property objectName of [object Object] which has only a getter
at mak$1.ReflectedEntity.mak$1.ReflectedObject [as constructor] (vrlink.mjs:818)
at new mak$1.ReflectedEntity (vrlink.mjs:903)
at mak$1.ReflectedEntityList.value (vrlink.mjs:1358)
at mak$1.WebLVCMessageCallbackManager.<anonymous> (vrlink.mjs:1155)
at mak$1.WebLVCMessageCallbackManager.processMessage (vrlink.mjs:1745)
at mak$1.WebLVCConnection.drainInput (vrlink.mjs:2139)
at SimLink.tick (SimLink.js:34)
This seems to be the offender when converting from IIFE modules to ES6. It says that there is no setter.
The code is not my creation, but it seemed like it should not have be a major effort to convert IIFE to ES6. The offending snippet is:
mak.VrfBackendStateRepository = function (objectName) {
/**
Unique string identifying entity
#property objectName
#type String
**/
this.objectName = objectName; //error generated on this line!
If you are wondering what this is, it is a object called mak.webLVConnection, which is created by this function in the IIFE code:
/**
Represents a connection to a WebLVC server.
clientName and port are required. webLVCVersion is optional (current version
supported by the WebLVC server will be in effect). serverLocation is optional
( websocket connection will be made to the host servering the javascript )
#class WebLVCConnection
#constructor
#param {String} clientName String representing name of the client federate
#param {Number} port Websocket port number
#param {Number} webLVCVersion WebLVC version number
#param {String} serverLocation Hostname of websocket server
**/
mak.WebLVCConnection = function (clientName, port, webLVCVersion, serverLocation, url) {
var self = this;
if (clientName == undefined) {
throw new Error("clientName not specified");
}
if (!(typeof clientName == "string" && clientName.length > 0)) {
throw new Error("Invalid ClientName specified");
}
if (port == undefined) {
throw new Error("Port not specified");
}
if (url == undefined) {
url = "/ws";
}
var websocket;
if (serverLocation == undefined) {
if (location.hostname) {
websocket = new WebSocket("ws://" + location.hostname + ":" + port + url);
}
else {
websocket = new WebSocket("ws://localhost:" + port + "/ws");
}
}
else {
websocket = new WebSocket("ws://" + serverLocation + ":" + port + url);
}
/**
Websocket connected to a WebLVC server.
#property websocket
#type WebSocket
**/
this.websocket = websocket;
/**
DIS/RPR-style identifier, used to generate new unique IDs for entities simulated
through this connection. Array of 3 numbers [site ID, host ID, entity number].
#property currentId
#type Array
**/
this.currentId = [1, 1, 0];
/**
Manages registration and invoking of message callbacks.
#property webLVCMessageCallbackManager
#type WebLVCMessageCallbackManager
**/
this.webLVCMessageCallbackManager = new mak.WebLVCMessageCallbackManager();
/**
Simulation clock
#property clock
#type Clock
**/
this.clock = new mak.Clock();
/**
Indicates whether timestamping is relative or absolute
(mak.TimeStampType.TimeStampRelative or
mak.TimeStampType.TimeStampAbsolute).
#property {Number} timeStampType
**/
this.timeStampType = mak.TimeStampType.TimeStampRelative;
/**
List of incoming messages. When messages are received, they are placed
in this queue. The drainInput() member function must be called regularly
to remove and process messages in this queue.
#property {Array} messageQueue
**/
this.messageQueue = new Array();
/**
Callback function invoked on receipt of a message. Calls
webLVCMessageCallbackManager.processMessage().
#method processMessage
#private
**/
this.processMessage = this.webLVCMessageCallbackManager.processMessage.bind(this.webLVCMessageCallbackManager);
/**
Callback function invoked when websocket connection is opened. Sends
the initial WebLVC connect message.
#method onopen
#private
**/
this.websocket.onopen = function () {
var connectMessage = {
MessageKind: mak.MessageKindEnum.Connect,
ClientName: clientName
}
if (webLVCVersion != undefined) {
connectMessage.WebLVCVersion = webLVCVersion;
}
if (self.websocket.readyState == 1) {
self.websocket.send(JSON.stringify(connectMessage));
}
};
/**
Callback function invoked when a WebLVC message is received. Parses the
the JSON message data and passes the resulting object to processMessage.
#method onmessage
#event {Object} JSON message
#private
**/
this.websocket.onmessage = function (event) {
//just in case
if (event.data == "ping")
return;
var message = JSON.parse(event.data);
if (message != null) {
self.messageQueue.push(message);
} else {
console.warn("onmessage - null message received");
}
};
/**
Callback function invoked when the websocket is closed.
#method onclose
#private
**/
this.websocket.onclose = function () {
console.debug("In websocket.onclose");
};
/**
Callback function invoked when an error in the websocket is detected.
Sends warning to console.
#method onerror
#private
**/
this.websocket.onerror = function () {
console.log("websocket onerror");
};
this.isOk = function () {
return this.websocket.readyState == 1;
}
};
mak.WebLVCConnection.prototype = {
constructor: mak.WebLVCConnection,
/**
Set the DIS/RPR-style application ID.
#method set applicationId
#param {Array} applicationId Array of 2 integers [site ID, host ID].
**/
set applicationId(applicationId) {
this.currentId[0] = applicationId[0];
this.currentId[1] = applicationId[1];
this.currentId[2] = 0;
},
/**
Returns next available DIS/RPR-style entity ID.
#method nextId
#return {Array} Array of 3 integers [site ID, host ID, entity number].
**/
get nextId() {
this.currentId[2]++;
return this.currentId;
},
/**
Register callback function for a given kind of message.
#method addMessageCallback
#param {Number} messageKind WebLVC MessageKind
#param callback Function to be invoked
**/
addMessageCallback: function (messageKind, callback) {
this.webLVCMessageCallbackManager.addMessageCallback(messageKind, callback);
},
/**
De-register callback function for a given kind of message.
#method removeMessageCallback
#param messageKind WebLVC MessageKind
#param callback Function to be invoked
**/
removeMessageCallback: function (messageKind, callback) {
this.webLVCMessageCallbackManager.removeMessageCallback(messageKind, callback);
},
/**
Send a WebLVC message to the server.
#method send
#param {Object} message
**/
send: function (message) {
try {
if (this.websocket.readyState == 1) {
this.websocket.send(JSON.stringify(message));
}
} catch (exception) {
console.log("Error sending on websocket - exception: " + exception);
}
},
/**
Send a time-stamped WebLVC message to the server.
#method sendStamped
#param {Object} message
**/
sendStamped: function (message) {
// Timestamp is hex string
var timeStamp = this.currentTimeForStamping().toString(16);
//message.TimeStamp = ""; // timeStamp;
this.send(message);
},
/**
Get the current simulation time for a time stamp.
#method currentTimeForStamping
#return {Number} Simulation time in seconds.
**/
currentTimeForStamping: function () {
if (this.timeStampType == mak.TimeStampType.TimeStampAbsolute) {
return this.clock.simTime();
}
else {
return this.clock.absRealTime();
}
},
/**
Iterate through message queue, calling processMessage() and then
removing each message. Should be called regularly from your
application.
#method drainInput
**/
drainInput: function () {
var message;
while (this.messageQueue.length > 0) {
message = this.messageQueue.shift();
this.processMessage(message);
}
},
/**
Closes the websocket connection. Calls the destroy method on its
WebLVCMessageCallbackManager data member.
#method destroy
**/
destroy: function () {
console.debug("In WebLVCConnection.destroy");
this.webLVCMessageCallbackManager.destroy();
this.websocket.close();
}
};
UMD modules, by definition, are CommonJS. The code above is just IIFE and relies on mak global.
IIFE wrapper function can be replaced with default or named ES module export:
const mak = {};
mak.MessageKindEnum = { ... };
...
export default mak;
Or with CommonJS export:
const mak = {};
mak.MessageKindEnum = { ... };
...
module.exports = mak;
did you try:
(function (mak) {
...
}(module.exports));
// instead of
// } (this.mak = this.mak || {}));

Use data from session storage web in Polymer

I have a website made with Polymer that when you log in, it returns you in the session storage a key userData with values docID, name, surname and surname2, and then it enters to the platform. Those values are stored in the session storage of the browser.
I want to use those values except the docID and bring it to my code for plot it in the log in view/page, but I don't know how to use the session storage to take those parameters.
I made a fake user but with local storage that works with last time of connection but I don't know how to use it with session and receiving data from a website. This is my script:
Polymer({
date: null,
timeDate: null,
keyStorage: 'lastConnection',
ready: function(){
this.storageDate();
this.timeDate = this.getLastDateConnection();
this.storageUser();
this.fakeUserName = this.getUser();
},
getLastDateConnection: function(){
var date = new Date(parseInt(localStorage.getItem(this.keyStorage)));
return [date.getHours(),('0'+date.getMinutes()).slice(-2)].join(':');
},
storageDate: function(){
localStorage.setItem(this.keyStorage, +new Date);
},
getUser: function(){
var name = [localStorage.getItem("firstname") + " " + localStorage.getItem("lastname")];
return name;
},
storageUser:function(){
localStorage.setItem("lastname", "Vader");
localStorage.setItem("firstname", "Dark");
}
});
I want to do something similar except I have to storage the user data with session storage and from a website (I don't know the info until someone gets logged), so I suppose that I shouldn't do a setItem and just made a getItem receiving the key "userData" from the website. Any help/idea? Thanks!
PS: Maybe should I store the user info in my local storage after I receive the userData from the session storage if I want to keep the username? What I want to do is something equal to what Google do with our gmail accounts (you logg-in and when you want to enter again, it stores your account).
Ok, so I think I got it.
in the ready function is to make the call of the function that storages the session storage with:
ready: function(){
this.setData();
this.myUser = this.storageUser();
},
setData: function() {
sessionStorage.setItem("userData",userData);
},
and then storage the session storage in the local making a parse of the object:
storageUser: function(){
var userData = sessionStorage.getItem("userData");
var myObject = JSON.parse(userData);
var userName = [myObject.name + " " + myObject.surname];
return userName;
},
This is working on principle.
I know this is an old post but for new people who land on this page, this session storage element might be of help. It's behaviour is exactly like local storage.
<!--
#license
Copyright (c) 2015 The PlatinumIndustries.pl. All rights reserved.
This code may only be used under the BSD style license.
-->
<link rel="import" href="../polymer/polymer.html">
<!--
Element access to Web Storage API (window.sessionStorage).
Keeps `value` property in sync with sessionStorage.
Value is saved as json by default.
### Usage:
`Ss-sample` will automatically save changes to its value.
<dom-module id="ls-sample">
<iron-sessionstorage name="my-app-storage"
value="{{cartoon}}"
on-iron-sessionstorage-load-empty="initializeDefaultCartoon"
></iron-sessionstorage>
</dom-module>
<script>
Polymer({
is: 'ls-sample',
properties: {
cartoon: {
type: Object
}
},
// initializes default if nothing has been stored
initializeDefaultCartoon: function() {
this.cartoon = {
name: "Mickey",
hasEars: true
}
},
// use path set api to propagate changes to sessionstorage
makeModifications: function() {
this.set('cartoon.name', "Minions");
this.set('cartoon.hasEars', false);
}
});
</script>
### Tech notes:
* * `value.*` is observed, and saved on modifications. You must use
path change notifification methods such as `set()` to modify value
for changes to be observed.
* * Set `auto-save-disabled` to prevent automatic saving.
* * Value is saved as JSON by default.
* * To delete a key, set value to null
* Element listens to StorageAPI `storage` event, and will reload upon receiving it.
* **Warning**: do not bind value to sub-properties until Polymer
[bug 1550](https://github.com/Polymer/polymer/issues/1550)
is resolved. session storage will be blown away.
`<iron-sessionstorage value="{{foo.bar}}"` will cause **data loss**.
#demo demo/index.html
#hero hero.svg
-->
<dom-module id="iron-sessionstorage"></dom-module>
<script>
Polymer({
is: 'iron-sessionstorage',
properties: {
/**
* SessionStorage item key
*/
name: {
type: String,
value: ''
},
/**
* The data associated with this storage.
* If set to null item will be deleted.
* #type {*}
*/
value: {
type: Object,
notify: true
},
/**
* If true: do not convert value to JSON on save/load
*/
useRaw: {
type: Boolean,
value: false
},
/**
* Value will not be saved automatically if true. You'll have to do it manually with `save()`
*/
autoSaveDisabled: {
type: Boolean,
value: false
},
/**
* Last error encountered while saving/loading items
*/
errorMessage: {
type: String,
notify: true
},
/** True if value has been loaded */
_loaded: {
type: Boolean,
value: false
}
},
observers: [
'_debounceReload(name,useRaw)',
'_trySaveValue(autoSaveDisabled)',
'_trySaveValue(value.*)'
],
ready: function() {
this._boundHandleStorage = this._handleStorage.bind(this);
},
attached: function() {
window.addEventListener('storage', this._boundHandleStorage);
},
detached: function() {
window.removeEventListener('storage', this._boundHandleStorage);
},
_handleStorage: function(ev) {
if (ev.key == this.name) {
this._load(true);
}
},
_trySaveValue: function() {
if (this._doNotSave) {
return;
}
if (this._loaded && !this.autoSaveDisabled) {
this.debounce('save', this.save);
}
},
_debounceReload: function() {
this.debounce('reload', this.reload);
},
/**
* Loads the value again. Use if you modify
* sessionStorage using DOM calls, and want to
* keep this element in sync.
*/
reload: function() {
this._loaded = false;
this._load();
},
/**
* loads value from session storage
* #param {boolean=} externalChange true if loading changes from a different window
*/
_load: function(externalChange) {
var v = window.sessionStorage.getItem(this.name);
if (v === null) {
this._loaded = true;
this._doNotSave = true; // guard for save watchers
this.value = null;
this._doNotSave = false;
this.fire('iron-sessionstorage-load-empty', { externalChange: externalChange});
} else {
if (!this.useRaw) {
try { // parse value as JSON
v = JSON.parse(v);
} catch(x) {
this.errorMessage = "Could not parse session storage value";
console.error("could not parse sessionstorage value", v);
v = null;
}
}
this._loaded = true;
this._doNotSave = true;
this.value = v;
this._doNotSave = false;
this.fire('iron-sessionstorage-load', { externalChange: externalChange});
}
},
/**
* Saves the value to localStorage. Call to save if autoSaveDisabled is set.
* If `value` is null or undefined, deletes localStorage.
*/
save: function() {
var v = this.useRaw ? this.value : JSON.stringify(this.value);
try {
if (this.value === null || this.value === undefined) {
window.sessionStorage.removeItem(this.name);
} else {
window.sessionStorage.setItem(this.name, /** #type {string} */ (v));
}
}
catch(ex) {
// Happens in Safari incognito mode,
this.errorMessage = ex.message;
console.error("sessionStorage could not be saved. Safari incoginito mode?", ex);
}
}
/**
* Fired when value loads from localStorage.
*
* #event iron-localstorage-load
* #param {{externalChange:boolean}} detail -
* externalChange: true if change occured in different window.
*/
/**
* Fired when loaded value does not exist.
* Event handler can be used to initialize default value.
*
* #event iron-localstorage-load-empty
* #param {{externalChange:boolean}} detail -
* externalChange: true if change occured in different window.
*/
});
</script>

Conference room availability in JavaScript

I am trying to create a room availability script for a conference room at my university. I decided to achieve it using jQuery by parsing a JSON feed of a public Google calendar and then displaying on the screen whether room is available or not.
I feel stupid, I have been fighting this problems for 3 days and no matter whether there is an appointment in Google calendar or not the script says that room is available. Could anyone offer a suggestion why this may be happening. I am not a programmer and I bet this is something really simple but I just can't seem to see it. Any help would be greatly appreciated!
A minimal working example on jsFiddle and below:
<html>
<head>
<title>Graduate Center Conference Room</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
// Declare global variables
var events = [];
var currentReservation = null;
var nextReservation = null;
var gclaData = 'http://www.google.com/calendar/feeds/4occ2bc4m626a3pgmirlm06q5s%40group.calendar.google.com/public/full?orderby=starttime&sortorder=ascending&futureevents=true&singleevents=true&max-results=2&alt=json';
// Parse Google Calendar Public JSON Feed and store in the events global array
$(document).ready(function () {
$.getJSON(gclaData, function (data) {
$.each(data.feed.entry, function (i, entry) {
var dtStart = new Date(entry["gd$when"][0].startTime);
var dtEnd = new Date(entry["gd$when"][0].endTime);
var dtSummary = entry.content.$t;
var dtTitle = entry.title.$t;
events[i] = {
'start': dtStart,
'end': dtEnd,
'title': dtTitle,
'summary': dtSummary
};
});
});
reservationInfo = '';
// sort events just in case (JSON should be sorted anyways)
events.sort(function (a, b) {
return a.start - b.start;
});
// current date
var dtNow = new Date();
// let's assume there are no current room reservations unless script detects otherwise.
// No reservations indicated by -1
currentReservation = -1;
// loop through the events array and if current time falls between start and end of a element in the array the mark it as a reservation currently in progress
for (var i in events) {
if (dtNow >= events[i].start && dtNow <= events[i].end) currentReservation = i;
}
// Print the result to a output div
if (-1 == currentReservation) {
reservationInfo = '<h1>ROOM AVAILABLE</h1>';
$('#output').html(reservationInfo);
} else {
reservationInfo = '<h1>ROOM OCCUPIED</h1>';
$('#output').html(reservationInfo);
}
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Some observations...
1) Do some refactor to your code and always do some debugging!
2) Your events variable is not the expected object since ajax calls are asynchronous and other code gets executed before getting into the callback that will fill your object. In other words, you need to wait for ajax call otherwise your object won't be the expected one (maybe will be undefined at first and after a moment, when ajax call finishes, an object with data).
Just to know, you can force an ajax call to be synchronous but that's NOT a good approach.
Try this:
I like to work this way, code it's way better organized:
Live Demo: http://jsfiddle.net/oscarj24/8HVj7/
HTML:
<div id="output"></div>
jQuery:
/*
* http://stackoverflow.com/questions/23205399/conference-room-availability-in-javascript
* #author: Oscar Jara
*/
/* Google calendar URL */
var url = 'http://www.google.com/calendar/feeds/4occ2bc4m626a3pgmirlm06q5s%40group.calendar.google.com/public/full?orderby=starttime&sortorder=ascending&futureevents=true&singleevents=true&max-results=2&alt=json';
/* Status list used to show final message to UI */
var statusList = {
'ROOM_A': 'Available',
'ROOM_O': 'Occupied',
'ERROR_DATA': 'No data found at Google calendar.',
'ERROR_PROCESS': 'There was an error checking room availability.'
};
/* Document onReady handler */
$(document).ready(function () {
getCalData(url);
});
/*
* Get Google calendar data by request.
* #param {String} url
*/
function getCalData(url) {
var statusCode;
$.getJSON(url, function (data) {
if (!$.isEmptyObject(data)) {
var events = parseCalData(data);
var curReserv = getCurrentReservation(events);
statusCode = getRoomStatusCode(curReserv);
} else {
statusCode = 'ERROR_DATA';
}
printRoomStatusToUI(statusCode, $('#output'));
}).fail(function (r) { // HTTP communication error
console.error(r);
});
};
/*
* Parse Google calendar data.
* #param {Object} data
* #return {Object} events
*/
function parseCalData(data) {
var events;
events = $.map(data.feed.entry, function (evt, i) {
var dt = evt['gd$when'][0];
return {
start: new Date(dt.startTime),
end: new Date(dt.endTime),
title: evt.title.$t,
summary: evt.content.$t
};
});
if (events) {
sortEvents(events); // Just in case
}
return events;
};
/*
* Sort Google calendar events.
* #param {Object} events
*/
function sortEvents(events) {
events.sort(function (a, b) {
return a.start - b.start;
});
}
/*
* Get/check for current reservation.
* If current time falls between start and end of an event,
* mark it as a reservation currently in progress.
* #param {Object} events
* #return {int} curReserv
*/
function getCurrentReservation(events) {
var curReserv;
if (events) {
var dtNow = new Date(); // Current datetime
curReserv = -1; // No reservations
for (var i in events) {
var dtStart = events[i].start;
var dtEnd = events[i].end;
if (dtNow >= dtStart && dtNow <= dtEnd) {
curReserv = i;
break;
}
}
}
return curReserv;
};
/*
* Get room availability statusCode.
* #param {int} curReserv
* #return {String} statusCode
*/
function getRoomStatusCode(curReserv) {
var statusCode = 'ROOM_A';
if (!curReserv) {
statusCode = 'ERROR_PROCESS';
} else if (curReserv && curReserv != -1) {
statusCode = 'ROOM_O';
}
return statusCode;
};
/*
* #private
* Get room status text.
* #param {String} statusCode
* #return {String}
*/
function getRoomStatusText(statusCode) {
return statusList[statusCode];
};
/*
* #private
* Check if statusCode is an ERROR one.
* #param {String} statusCode
* #return {Boolean}
*/
function isErrorStatus(statusCode) {
return (statusCode.indexOf('ERROR') > -1);
};
/*
* Print room availability to UI.
* #param {String} statusCode
* #param {Object} elem
*/
function printRoomStatusToUI(statusCode, elem) {
var statusText = getRoomStatusText(statusCode);
var isError = isErrorStatus(statusCode);
if (statusText && $.trim(statusText) != '') {
if (!isError) {
statusText = '<h1>Room is: ' + statusText + '</h1>';
}
elem.html(statusText);
}
};
You can quickly check what state a variable is by using:
console.log(variableName);
This will output the results of the variable in your browser console tab (in Developer Tools).
In your case, I did console.log(events); where the events were to be looped, and I discovered that events were not being set. After some debugging, I determined that the code was $.getJSON() function wasn't completing 100% before the code below it was running (most likely because the ajax request takes time).
To fix this, I've moved all of your code that parses the events within the $.getJSON() function so that the events are properly retrieved and set before parsing the data.
Your code will look like this now:
Working JSFiddle: http://jsfiddle.net/Mf8vb/4/
// Declare global variables
// Parse Google Calendar Public JSON Feed and store in the events global array
$(document).ready(function () {
var events = [];
var currentReservation = null;
var nextReservation = null;
var gclaData = 'http://www.google.com/calendar/feeds/4occ2bc4m626a3pgmirlm06q5s%40group.calendar.google.com/public/full?orderby=starttime&sortorder=ascending&futureevents=true&singleevents=true&max-results=2&alt=json';
$.getJSON(gclaData, function (data) {
$.each(data.feed.entry, function (i, entry) {
var dtStart = new Date(entry["gd$when"][0].startTime);
var dtEnd = new Date(entry["gd$when"][0].endTime);
var dtSummary = entry.content.$t;
var dtTitle = entry.title.$t;
events[i] = {
'start': dtStart,
'end': dtEnd,
'title': dtTitle,
'summary': dtSummary
};
});
reservationInfo = '';
// sort events just in case (JSON should be sorted anyways)
events.sort(function (a, b) {
return a.start - b.start;
});
// current date
var dtNow = new Date();
// let's assume there are no current room reservations unless script detects otherwise.
// No reservations indicated by -1
currentReservation = -1;
// loop through the events array and if current time falls between start and end of a element in the array the mark it as a reservation currently in progress
for (var i in events) {
if (dtNow >= events[i].start && dtNow <= events[i].end)
currentReservation = i;
}
// Print the result to a output div
if (-1 == currentReservation) {
reservationInfo = '<h1>ROOM AVAILABLE</h1>';
$('#output').html(reservationInfo);
} else {
reservationInfo = '<h1>ROOM OCCUPIED</h1>';
$('#output').html(reservationInfo);
}
});
});

jsdoc documentation functions inside module

I have the following code:
/**
* #fileOverview Various tool functions.
* #version 3.1.2
*/
define(function (require, exports, module) {
"use strict";
/**
* A module that handles file
* #module fileHandler
*/
/// Form to open a new set of files
var newFileForm = require("pvsioweb/forms/newFileForm");
var formEvents = require("pvsioweb/forms/events");
/// Reference to current project, main.js passes it by using fileHandler_setProject
var currentProject;
/**
* this is a function
* #param p1 First parameter
* #param p2 Second parameter
* #return {String} some value
*/
function setProject(project)
{
currentProject = project;
}
/**
* Create a new file, it is going to be shown in the listview: #pvsFiles
*
* #param name: name of the file
* #param content: textual content of the file
*
* #returns void
*
*/
function new_file(name, content )
{
var default_name = "MyTheory.pvs";
var default_content = "MyTheory" + " THEORY BEGIN \nEND MyTheory" ;
if( ! name ) { name = default_name; }
if( ! content ) { content = default_content; }
currentProject.addSpecFile(default_name, default_content);
renderSourceFileList(currentProject.pvsFiles());
}
/**
* Display new file form, invoke function open_file (see below)
*
* #returns void
*
*/
function open_file_form()
{
newFileForm.create().addListener(formEvents.FormCancelled, function (e) {
console.log(e);
e.form.remove();
}).addListener(formEvents.FormSubmitted, function (e) {
console.log(e);
e.form.remove();
open(e.formJSON);
});
}
/**
* Open file specified in data, data must have this structure: ???? FIXME
*
* #param data: ??? FIXME
*
* #returns void
*
*/
function open_file(data)
{
var q = queue(), i;
for (i = 0; i < data.pvsSpec.length; i++) {
q.defer(createFileLoadFunction(data.pvsSpec[i]));
}
q.awaitAll(function (err, res) {
currentProject.saveNew(function (err, res) {
console.log({err: err, res: res});
renderSourceFileList(currentProject.pvsFiles());
});
});
}
/********* Exported Function ******************/
module.exports = {
new_file: function (name, content) {
return new_file(name, content);
},
open_file_form: function () {
return open_file_form();
},
open_file: function () {
return open_file();
},
setProject: function (project) {
return setProject(project);
}
};
/***********************************************/
});
I tried to make some output by using jsdoc, but it seems to recognize just the word module and the header at the beginning of the file.
How can I fix to see also the documentation about the functions?
Thanks
I'm not sure I understand the question. Are you trying to generate documentation with jsdoc? If so, you'll need to add the jsdoc comments to each function. Also, your exports could be greatly simplified:
module.exports = {
new_file: new_file,
open_file_form: open_file_form,
open_file: open_file,
setProject: setProject
};

Categories

Resources