how to send bytes from bloomrpc? - protocol-buffers

I defined .proto file like,
test.proto
syntax = "proto3";
package unary;
service Greeter {
rpc greet (Request) returns (Response) {}
}
message Request {
bytes username = 1;
}
message Response {
string message = 1;
}
and When i import this test.proto file in bloomrpc it genrate json like,
{
"username": {
"type": "Buffer",
"data": [
72,
101,
108,
108,
111
]
}
}
So,can any one explain what is this format of json. what this type as buffer? and data[] list?

Related

How to represent google.protobuf.Any to JSON?

I have a request with a field of google.protobuf.Any type. I already checked if my gRPC service is working and I set up the envoy to transcode HTTP/JSON to gRPC. But the envoy keeps giving me an error because of the google.protobuf.Any type.
metadata: invalid value Invalid type URL, unknown type: metadata for type Any
I constructed my request in JSON format like the one below. Is anyone know how to format google.protobuf.Any type?
{
"type": "create",
"metadata": {
"#type": "type.googleapis.com/metadata",
"credentials": {
"username": "username",
"password": "password"
},
"context": {
"key": "value"
}
}
}
package/credentials.proto
message Credentials {
string username = 1;
string password = 2;
}
package/metadata.proto
message Metadata {
package.Credentials credentials = 1;
google.protobuf.Struct context = 2;
}
package/service.proto
message CreateOperationRequest {
string type = 1;
google.protobuf.Any metadata = 2;
}

does reportStateAndNotification support multiple device state reporting?

I am trying to report the status of a couple of devices via API and I am getting this error
Request payload:
{
"requestId":"3310672920401175639",
"agentUserId":"5d8f3dd42ce05140dc1c6a20",
"payload":{
"devices":{
"states":[
{
"5de28e041729ec0cb40ba906":{
"on":true
}
},
{
"5df49862f53ffa4c1452a448":{
"on":false,
"brightness":100
}
}
]
}
}
}
Response:
{
"error":{
"code":400,
"message":"Invalid JSON payload received. Unknown name "states" at 'payload.devices': Proto field is not repeating, cannot start list.",
"status":"INVALID_ARGUMENT",
"details":[
{
"#type":"type.googleapis.com/google.rpc.BadRequest",
"fieldViolations":[
{
"field":"payload.devices",
"description":"Invalid JSON payload received. Unknown name "states" at 'payload.devices': Proto field is not repeating, cannot start list."
}
]
}
]
}
}
can "states" hold more than one status of the device? or am I doing something wrong with this?
The states value in the payload should be an object with each unique device id as a key. It should not be returned with these wrapped into an array. So your request payload should look more like this:
{
"requestId":"3310672920401175639",
"agentUserId":"5d8f3dd42ce05140dc1c6a20",
"payload": {
"devices": {
"states": {
"5de28e041729ec0cb40ba906": {
"on": true
},
"5df49862f53ffa4c1452a448": {
"on": false,
"brightness": 100
}
}
}
}
}

How to make GraphQL resolver for list of objects returned by API using Apollo?

I am new to GraphQL and want to run my first app. I have seen several examples but they have used several libraries and i just want simple example.
I have seen https://www.youtube.com/watch?v=hLcAlln-D_s
My Index.js code
const { ApolloServer, gql } = require("apollo-server");
const fetch = require("node-fetch");
const typeDefs = `
type Query {
getApplicant: [Applicant]
}
type Applicant {
FiscalYear:String
JobNumber: String
JobDescription: String
AppsReceived: Int
Female: Int
Male: Int
UnknownGender: Int
Black: Int
Hispanic: Int
Asian: Int
Caucasian: Int
AmericanIndian:Int
Filipino: Int
UnknownEthnicity: Int
} `;
const url = `http://localhost:52993/api/values`;
const resolvers = {
Query: {
getApplicant: async () => {
const response = await fetch(url).then(res => res.json());
console.log(response);
return response;
}
}
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Data returned from API
[{ "FiscalYear": "2013-2014",
"JobNumber": "9206 OP 2014/04/18",
"JobDescription": "311 DIRECTOR 9206",
"AppsReceived": 54,
"Female": 20,
"Male": 31,
"UnknownGender": 3,
"Black": 25,
"Hispanic": 18,
"Asian": 1,
"Caucasian": 6,
"AmericanIndian": 0,
"Filipino": 0,
"UnknownEthnicity": 4
},
{
"FiscalYear": "2013-2014",
"JobNumber": "1223 P 2013/08/09",
"JobDescription": "ACCOUNTING CLERK 1223",
"AppsReceived": 648,
"Female": 488,
"Male": 152,
"UnknownGender": 8,
"Black": 151,
"Hispanic": 204,
"Asian": 123,
"Caucasian": 62,
"AmericanIndian": 3,
"Filipino": 79,
"UnknownEthnicity": 26
}]
when I query data it always displays null.What I am missing?
I have tried another API and it worked well with the same code, just changed the schema related things. Although my .net core Web API was returning same data as mentioned but to make my resolver work, I did 2 things
I returned the following from the API Get method:
var myJObject = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Applicant>>(json);
return Ok(myJObject);
In schema I modified "Applicant" properties to camel case. As I saw my API was returning camel case properties which are not getting mapped to my "Applicant" schema
I spent hours on that so I found it worth sharing.

perform nested query in Python Graphene with distinct types in schema

I have the following data structure coming from a database:
[
{
'time': '2019-07-19T12:57:17Z',
'bizLocation': 'urn:epc:id:sgln:bizLocation.Company.3',
'city': 'dallas',
'countryCode': 'US',
'humid': 49,
'sID': '40:61:32:22:11:00',
'site': 'factory',
'stype': 'BME280',
'temp': 22.941
}
]
I wish to create a GraphQL API to query the Database and provide the query in the following output:
[
{
sID: String (same as sID),
sType: String (same as sType),
bizLocation: String (same as bizLocation),
values: [
{
timestamp: Datetime (same as time),
value: Float (value of 'temp')
mType: 'temp'
},
{
timestamp: Datetime (same as time),
value: Float (value of 'humid'),
mType: 'humid'
}
]
}
]
I am using Graphene to just test if it might work. Currently I am just playing around with the idea and tried to make the following GraphQL Schema:
type SensorDoc {
sID: String
sType: String
bizLocation: String
values: [SensorData]
}
type SensorData {
timestamp: String
value: Float
mType: String
}
Translated to Graphene is as follows:
import graphene
class SensorData(graphene.ObjectType):
timestamp = graphene.DateTime()
value = graphene.Float()
mType = graphene.String()
class SensorDoc(graphene.ObjectType):
sId = graphene.String()
sType = graphene.String()
bizLocation = graphene.String()
values = graphene.List(SensorData)
class Query(graphene.ObjectType):
sensor_data = graphene.List(SensorDoc)
def resolve_sensor_data(self, info):
# DB Query Logic Here!!
output = [] # output to return
for each_point in list_result:
SensorDoc(sId=each_point['sID'], sType=each_point['stype'],
bizLocation=each_point['bizLocation'],
SensorData(timestamp=each_point['time'],
value=each_point['humid'], mType='humid') # <---- This is a SyntaxError
)
output.append(SensorDoc)
return output
This wouldn't work since SensorData won't pass as keyword argument.
I am completely new to trying out Graphene and was wondering how is this achievable when the query should look like the following:
query{
sensorData {
sID
sType
bizLocation
values {
timestamp
value
}
}
}
I was able to solve this issue by resolving the values within the SensorDoc class as follows:
class SensorData(graphene.ObjectType):
timestamp = graphene.String()
temp = graphene.Float()
humid = graphene.Float()
class SensorDoc(graphene.ObjectType):
sId = graphene.String()
sType = graphene.String()
bizLocation = graphene.String()
values = graphene.List(SensorData)
def resolve_values(parent, info):
# DB Query Logic
output = [] # output to return
for each_point in list_result:
output.append(
SensorData(timestamp=each_point['time'], temp=each_point['temp'], humid=each_point['humid'])
)
return output
And Within the main Query Class, kept the resolve_sensor_doc resolver:
class Query(graphene.ObjectType):
sensor_doc = graphene.List(SensorDoc)
def resolve_sensor_doc(self, info):
# DB Query Logic
output = []
for each_point in list_result:
output.append(
SensorDoc(
sId=each_point['sID'],
sType=each_point['stype'],
bizLocation=each_point['bizLocation']
)
)
return output
Finally the execution:
schema = graphene.Schema(query=Query)
result = schema.execute(
'''
query {
sensorDoc{
sId
sType
bizLocation
values {
timestamp
temp
humid
}
}
}
'''
)
items = dict(result.data.items())
print(json.dumps(items, indent=4))
Provides me the the output as follows:
{
"sensorDoc": [
{
"sId": "60:64:05:9C:DF:F2",
"sType": "BME280",
"bizLocation": "urn:epc:id:sgln:bizLocation.3",
"values": [
{
"timestamp": "2019-07-19T12:57:17Z",
"temp": 22.941,
"humid": 49.0
},
{
"timestamp": "2019-07-19T12:57:19Z",
"temp": 22.981,
"humid": 47.0
},
{
"timestamp": "2019-07-19T12:57:21Z",
"temp": 23.001,
"humid": 47.0
}
]
},
{
"sId": "60:64:05:9C:DF:F2",
"sType": "BME280",
"bizLocation": "urn:epc:id:sgln:bizLocation.3",
"values": [
{
"timestamp": "2019-07-19T12:57:17Z",
"temp": 22.941,
"humid": 49.0
},
{
"timestamp": "2019-07-19T12:57:19Z",
"temp": 22.981,
"humid": 47.0
},
{
"timestamp": "2019-07-19T12:57:21Z",
"temp": 23.001,
"humid": 47.0
}
]
},
{
"sId": "60:64:05:9C:DF:F2",
"sType": "BME280",
"bizLocation": "urn:epc:id:sgln:bizLocation.3",
"values": [
{
"timestamp": "2019-07-19T12:57:17Z",
"temp": 22.941,
"humid": 49.0
},
{
"timestamp": "2019-07-19T12:57:19Z",
"temp": 22.981,
"humid": 47.0
},
{
"timestamp": "2019-07-19T12:57:21Z",
"temp": 23.001,
"humid": 47.0
}
]
}
]
}

How to assign a single object to a list?

I'm working with an API rest and it returns me two types of json, object and array.
Object(When there is only one record in the database):
{ "complain": { "id": "1" , "description": "hello", "date": "2017-01-24 11:46:22", "Lat": "20.5204446", "Long": "-100.8249097" } }
Array(When there is more than one record in the database):
{ "complain": [ { "id": "1" , "description": "hello", "date": "2017-01-24 11:46:22", "Lat": "20.587446", "Long": "-100.8246490" }, { "id": "2" , "description": "hello 2", "date": "2017-01-24 11:50:12", "Lat": "20.529876", "Long": "-100.8249097" } ] }
The code I use to consume the json is as follows:
content = await response.Content.ReadAsStringAsync();
var token = JToken.Parse(content);
if (token["complain"] is JArray)
{
var jsonArray = JsonConvert.DeserializeObject<RootArray>(content);
}
else if (token["complain"] is JObject)
{
var jsonObject = JsonConvert.DeserializeObject<RootObject>(content);
}
When it comes to a json array if I can add it to a listview:
myList.ItemsSource = jsonArray.listArray;
But if it is an object I can not and I get the following error:
Cannot implicitly convert type Object to IEnumerable.
Finally I was able to solve my error, it was just a matter of creating a list and adding the deserialized json object.
var jsonObject = JsonConvert.DeserializeObject<RootObject>(content);
List<Complain> simpleList = new List<Complain>();
simpleList.Add(jsonObject.ComplainObject);
myList.ItemsSource = simpleList;
The class to deserialize the Json object:
public class RootObject
{
[JsonProperty("complain")]
public Complain ComplainObject { get; set; }
}

Resources