Generating dart code from single JSON input - dart

I'm trying to build a dart package which generates API source code from OData JSON representation file. I tried using source_gen, but it appears to generate code based on annotations or existing source code (e.g. JSON serializer generated code for existing class).
Goal: Generate multiple dart codes based on JSON data. E.g.: Say my JSON is:
{
"user": {
"income": "Decimal", //Decimal is the type, which I translate it into dart type
}
}
and my generated code would be:
user.dart:
import "package:decimal/decimal.dart";
class User {
final Decimal age;
User(this.age);
}

What are you trying to do is already implemented, when it comes to API description.
You can generate code with classes from .proto or swagger .yaml/ .json files.
Proto file generation for gRPC API
Proto file example:
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}
message SearchResponse {
...
}
Swagger rest api code generation from .yml/json files
Look:

Related

Data Gets Converted when passed to CREATE_STREAM

I have created an UI5 Application to read a file and send it to a custom OData Service in the Backend.
onUploadFile: function() {
var oFileUpload =
this.getView().byId("fileUploaderFS");
var domRef = oFileUpload.getFocusDomRef();
var file = domRef.files[0];
var that = this;
var reader = new FileReader();
var ftype = file.type;
reader.readAsArrayBuffer(file);
reader.onload = function(evt) {
var vContent = evt.currentTarget.result
console.log(vContent);
var hex = that.buf2hex(vContent);
that.updateFile(hex, ftype);
}
},
buf2hex: function(buffer) {
return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join('');
}
When I print the content of hex on the console before sending it to the backend, the data starts with 89504e470d0a1a0a0000000d49484 ....
Even before sending the data in the payload to Odata Service it shows the correct data
Here is the Odata Service
Inside the Create Stream the data when received, is getting converted into something else. As a result the image that has been saved is not opening.
I tried to change the Data Type of Content in SEGW to Binary and it did not work. I also tried to convert the data in the create_stream but in vain. At last I tried reading the data in UI5 in different formats but of no use.
This whole Odata service works perfectly fine when I load the data through Postman Application.
Please help me resolve this Issue. Thanks In Advance.
The sap.ui.unified.FileUploader has everything built in. No need for conversions from Buffer to hex.
Make sure that your FileUploader knows where to upload the file
<unified:FileUploader xmlns:unified="sap.ui.unified"
id="fileUploaderFS"
uploadUrl="/sap/opu/odata/sap/Z_TEST_SRV/FileSet"
/>
The attribute uploadUrl points to the media entity for which you implemented the create_stream method.
Then when the upload is triggered via button press, simply get the FileUploader, set the token (for security reasons when doing a POST request), and fire the upload method.
onUploadFile: function () {
const oFileUpload = this.getView().byId("fileUploaderFS");
const sToken = this.getModel("nameOfTheModel").getSecurityToken();
const oTokenParam = new FileUploaderParameter({
name: "x-csrf-token",
value: sToken
});
oFileUpload.removeAllHeaderParameters()
oFileUpload.addHeaderParameter(oTokenParam);
oFileUpload.upload();
}
To use FileUploaderParameter, make sure to import it at the beginning:
sap.ui.define([
// ...,
"sap/ui/unified/FileUploaderParameter"
], function (/*..., */FileUploaderParameter) {
// ...
Now about your File entity. When working with it via create_stream or read_stream, you don't use the entity structure but is_media_resource. This means your entity doesn't need a property content. Or most of the other properties (except a unique id and the mime type). All other properties would only be used if you want to do one of the CRUD methods (which happens almost never when dealing with streams).

in_app_purchase how do I get the data needed for android verification from the serverVerificationData

I am trying to implement server side verification for IAP's in my flutter app. I am using the package
https://pub.dev/packages/in_app_purchase
version: ^0.3.4+8
And I am confused how I get the data to verify my purchase for android and IOS. In the documentation they say
"or verify the data using your own server with
serverVerificationData."
This string seems to return some kind of encoded string. How do I then extract the needed data from this string? I tried base64Decode() since the localVerificationData is base64Encoded but this did not work.
Android needs a package name, purchase id and purchaseToken. And Ios needs a object receipt-data. I am confused on how I am to get that data from the serverVerificationData string.
I am currently implementing android first.
The the localVerificationData documentation says
The data used for local verification.
If the source is IAPSource.AppStore, this data is a based64 encoded
string. The structure of the payload is defined using ASN.1. If the
source is IAPSource.GooglePlay, this data is a JSON String.
So the serverVerificationData must be different from the localVerificationData then since it doesn't look like JSON at all. I am also not sure if it is safe to post the serverVerificationData here since it may contain sensitive information.
This is a string similar to the one I got on android only I changed all the letters, numbers etc. So it's just about the format
zdfdzcdshxvbxmgbafdxvdzt.JK-GR58OHRPOGFEFHEGVEACBEIFDAPDH_EFHEWFEHFHPEGVERBWBASZWDAWODPAWD-HDSWCGOEWFP-EFPEQFHPEDHEWYIFEWFUWEFDASCNAQWFDefphFEQUIWEFpofgewpfFEWHFPWEF
In the repo they show that they call the _verifyPurchase(purchase); which has no implementation in the example.
https://github.com/flutter/plugins/tree/master/packages/in_app_purchase#listening-to-purchase-updates
https://github.com/flutter/plugins/blob/5a183ac54a515be096d01f3a35546c5d89a30dca/packages/in_app_purchase/example/lib/main.dart#L350
And they say you should always verify
https://github.com/flutter/plugins/blob/5a183ac54a515be096d01f3a35546c5d89a30dca/packages/in_app_purchase/example/lib/main.dart#L328
This is my current code
Future<dynamic> verifyAndroid(PurchaseDetails details) async {
DatabaseService databaseService = Get.find<DatabaseService>();
String verificationData = details.verificationData.serverVerificationData;
// zdfdzcdshxvbxmgbafdxvdzt.JK-GR58OHRPOGFEFHEGVEACBEIFDAPDH_EFHEWFEHFHPEGVERBWBASZWDAWODPAWD-HDSWCGOEWFP-EFPEQFHPEDHEWYIFEWFUWEFDASCNAQWFDefphFEQUIWEFpofgewpfFEWHFPWEF
String packageName = ''; //get from verificationData
String productId = ''; //get from verificationData
String purchaseToken = ''; //get from verificationData
final response = await databaseService.verifyInAppPurchaseAndroid(packageName, productId, purchaseToken);
return response;
}
It turned out that the data was in the detail.verificationData.localVerificationData instead of the detail.verificationData.serverVerificationData and detail.verificationData.serverVerificationData is the purchase token on Android.

Zapier trigger that returns file: what is the format of the z.dehydrateFile call?

I am writing a Zapier trigger that will return a file. I understand that my trigger endpoint does not return the contents of the file, but rather a pointer to it.
All the example documentation shows the JavaScript example:
var Zap = {
your_trigger_post_poll: function(bundle) {
var records = z.JSON.parse(bundle.response.content);
return _.map(records, function(record) {
// if you just do url, we'll include any standard authentication headers
record.file = z.dehydrateFile('https://yoursite.com/files/download/' + record.id);
return record;
});
}
}
I am not writing my trigger in JavaScript. I would like to return the data in the correct format, but I can't find any examples of what that should be.
What is the output of z.dehydrateFile? Can you provide a JSON example?
If you want to return a file form your trigger to Zapier, you need to return the URL where Zapier can access that file as a record named 'file'.
If you want your trigger to return "converted_csv_file.xlsx" which can be found on your web server, your trigger would return the following JSON:
{
"file": "https://goodgrids.com/converted_spreadsheets/converted_csv_file.xlsx"
}
Note that the URL matters. The last part of the URL will be used as the file name. This is normal when serving up static files. However, if your service generates files on the fly, make sure that you have the file name as part of the URL, even if the actual key used to access the file is somewhere else in your URL.
{
"file": "https://goodgrids.com/converted_spreadsheets/9234659832475982372345876/converted_csv_file.xlsx"
}
Suggestion to Zapier: Please look at the Content-Disposition header returned when reading the file, to see if it contains a filename.

How to access swagger yaml defined objects from javascript

I used Swagger Yaml to describe an endpoint and generate the mock server. The existing endpoint (that I'm mocking) doesn't follow RESTful principles 100%, so I simply want to overwrite the response that is returned by the mock server. The simple server code is shown below:
var swagger = require('swagger-server');
var server = swagger('map-cache.yaml');
var port = 7072;
server.post('/map-qa_trunk/v2/getData', function(req, res, next) {
var foo = {
err : 123,
msg : "error message"
};
res.json(foo);
});
server.listen(port, function() {
console.log('Map Cache Mock Server is now running at http://localhost:' + port);
});
In the Yaml definition, there is an object defined called MapResponseData, how do I create an instance of this object so that I can populate it as needed and return in the res.json()? Something similar to below:
var response = getMapResponseData(); // don't know what this call should be
response.fieldA = 123;
res.json(response);
I am guessing this should be possible, since Swagger parsed the YAML file and is aware of all definitions that were specified.
Try outputting the request object to console.log to see if you can find reference to the swagger definition. Another option would be to pull the parsed swagger definition from the yaml file (using js-yaml for example) and extracting from there.
However, my best advice is to use swagger-tools instead of swagger-server. The swagger-server package is alpha version and has fewer downloads, revisions, and users than swagger-tools. Benefit of swagger-tools is that it will be actively maintained and there is a larger community that can support you. To convert your project to swagger-tools, use swagger.io > Swagger Editor > Online Editor > Paste yaml in left pane > Generate Server > Node.js
In swagger-tools the entire Swagger Yaml definition is contained in each request object:
req.swagger.swaggerObject
and you can pull the response object definitions from that as needed.

How do I create a Siesta transformer for an API endpoint that contains a JSON array?

I'm building an app that needs to make a GET request to the API endpoint https://thecountedapi.com/api/counted using the Siesta framework. The endpoint returns a JSON array, just like an endpoint like https://api.github.com/users/ebelinski/repos, which is used in the Siesta example Github Browser. As a result, I'm trying to make my app use Siesta in the say way that one does. I create a service:
let API = Service(baseURL: "https://thecountedapi.com/api")
Then a transformer for my endpoint in application:didFinishLaunchingWithOptions:
API.configureTransformer("/counted") {
($0.content as JSON).arrayValue.map(Incident.init)
}
Where Incident is a struct with an initializer that takes in a JSON object.
Then in my view controller, I create a resource:
let resource = API.resource("/counted")
and in viewDidLoad:
resource.addObserver(self)
and in viewWillAppear:
resource.loadIfNeeded()
Then I have the following function in my VC to listen to changes:
func resourceChanged(resource: Resource, event: ResourceEvent) {
print(resource.jsonArray)
if let error = resource.latestError {
print(error.userMessage)
return
}
if let content: [Incident] = resource.typedContent() {
print("content exists")
incidents = content
}
print(incidents.count)
}
But when I run my app, I get mixed results. print(resource.jsonArray) just prints [], I have an error message Cannot parse server response, and if I set Siesta.enabledLogCategories = LogCategory.detailed, I can see the error mesage [Siesta:StateChanges] Siesta.Resource(https://thecountedapi.com/api/counted)[] received error: Error(userMessage: "Cannot parse server response", httpStatusCode: nil, entity: nil, cause: Optional(Siesta.Error.Cause.WrongTypeInTranformerPipeline(expectedType: "JSON", actualType: "__NSCFArray", transformer: Siesta.ResponseContentTransformer<SwiftyJSON.JSON, Swift.Array<TheCountedViewer.Incident….
If I comment out the whole transformer, I have some success in that print(resource.jsonArray) prints out the correct array from the endpoint. So my transformer must be wrong in some way, but I think I'm using basically the same transformer as in Github Browser:
service.configureTransformer("/users/*/repos") {
($0.content as JSON).arrayValue.map(Repository.init)
}
Am I missing something?
The key clue to your problem is buried in that (perhaps not ideally helfpul) log message:
Siesta.Error.Cause.WrongTypeInTranformerPipeline
expectedType: "JSON"
actualType: "__NSCFArray"
It’s saying that your transformer expected an input type of JSON, which makes sense — you said as much with ($0.content as JSON). However, it got the type __NSCFArray, which is the secret internal backing type for NSArray. In other words, it expected a SwiftyJSON value, but it got the raw output of NSJSONSerialization instead.
Why? The GithubBrowser project includes an NSDict/NSArray → SwiftyJSON transformer which it configures in the parsing stage. The model transformers in that project all depend on it.
To use SwiftyJSON in the same way in your project, you’ll need to include that transformer from the example project in yours:
private let SwiftyJSONTransformer =
ResponseContentTransformer
{ JSON($0.content as AnyObject) }
And then when setting up your service:
service.configure {
$0.config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
}
(Note that you might want to create the ResponseContentTransformer with transformErrors: true if you are interested in errors.)
An alternative way to use SwiftyJSON, which is not quite as pretty but requires less setup, is to manually wrap things in JSON in each individual response transformer:
service.configureTransformer("/users/*/repos") {
JSON($0.content as AnyObject).arrayValue.map(Incident.init)
}

Resources