Generate static Javascript client from Swagger for use in React Native - javascript

I'm building a React Native app that will consume an API with Swagger 2.0 definition. I went to Swagger's repo at https://github.com/swagger-api/swagger-codegen#where-is-javascript and it points to their Javascript generator at https://github.com/swagger-api/swagger-js.
The problem is that the generator is dynamic, and since I'll be embedding the client in a mobile app, dynamic generator is not an option. They also say that there's a third party project available at https://github.com/wcandillon/swagger-js-codegen, which says that the project is no longer maintained and points back to https://github.com/swagger-api/swagger-codegen. (while that 3rd party generator works, I don't want to use a deprecated tool that might break any time since I'll be updating the API client when new endpoints arrive. And that tool also doesn't generate really good code anyway as it says in its own repo.)
At this point I'm stuck. What is the supported way of generating a static Javascript client from Swagger definition for use in React Native?

You can use Swagger Codegen to generate a javascript client sdk. However, the javascript code used in it will not work with React Native's fetch implementation. To overcome that, you can simply extend the implementation of ApiClient to use the React Native fetch like:
class CustomApiClient extends ApiClient {
callApi(path, httpMethod, pathParams,queryParams,collectionQueryParams, headerParams, formParams, bodyParam,authNames, contentTypes, accepts,returnType, callback) {
return fetch(`${this.basePath}${path}`,
{
method: httpMethod
});
}
}
Later using it in your other methods such as
class CustomUsersApi extends UsersApi {
constructor() {
super(new CustomApiClient());
}
}
For a detailed implementation on this, you can refer the blog post https://medium.com/#lupugabriel/using-swagger-codegen-with-reactnative-4493d98cac15

Related

How to manage data for the tests?

I have only one account - admin by default. I need to change user permissions to non-admin one. I believe that I have few options available (not great yet can be used)
Create a new endpoint on a server just for testing - to make it possible for non-admin user to update those permissions. This idea seems pretty odd to me to change something like that.
Have multiple users to be able to switch between them for different roles (all in all not that simple for now).
Connect to db within tests and make those changes on db - probably easiest option
Is it OK to create new endpoints for testing e.g. /publish-cypress? Is it OK to populate the database just for tests by running some operations on db?
On my personal opinion you shouldn't create testing endpoint.
What you should be testing is the method that will be called by these routes (Your service), and for front-end you can 'fake' these call to the api.
The simplest way to do that is to use something similar ton interfaces (you might want to look at typescript ;) )
An example to fake these calls in your tests:
I'll go with typescript as it'll be mush easier to understand (less code)
//here you define all calls possible to your api
//dont forget to always pass the gateway by reference so that you can change whenever you want between fake & real
interface MyGateway {
changeUserPermission(userId, permissions);
}
//here do the actual implementation that will be used by your app
class MyApiGateway implements MyGateway {
public changeUserPermission(userId, permissions) {
//here is your real api call with fetch, axios or whatever
fetch('http://example.com/perms')...
}
}
//now you can do another implementation for testing purposes
class MyTestGateway implements MyGateway {
//here you can return hard values or do whatever you want so that your app doesn't depends on you backend
public changeUserPermission(userId, permissions) {
console.log(`Updating ${userId} is ${permissions}`);
}
}

How to retrieve work items from Azure DevOps extension?

I successfully followed Microsoft's tutorial to create an extension.
I'm trying to get all the work-items of certain sprint, but to be honest, I'm lost...
I'm not sure what to look for - I have the VSS object, with which I can require additional services (such as TFS/WorkItemTracking/Services or TFS/WorkItemTracking/RestClient).
I found some examples like this one, but couldn't find an API to retrieve or query work items.
Do I need a JS object for that, or is it accomplished via some REST call?
You are nearly there.
You need the WIT RestClient (assuming you are using Typescript):
import { WorkItemTrackingHttpClient, getClient } from "TFS/WorkItemTracking/RestClient";
With that you can do
const witClient = ((getClient()) as WorkItemTrackingHttpClient);
and then
const result = await witClient.queryByWiql({ query: query });
The WorkItemTrackingHttpClient is all you need to manipulate work items.
EDIT: You could also have a look at the new SDK and API. But unfortunately its lacking a lot on the documentation side. Although there are some samples.
To query work items, you can can also check this page for WorkItemTrackingHttpClient2_2 client API.
IPromise<Contracts.WorkItemQueryResult> queryById(id, project, team)
IPromise<Contracts.WorkItemQueryResult> queryByWiql(wiql, project, team)
This is also an example about how to get WorkItemTrackingHttpClient and to call Api on Microsoft docs site.

Is there any way to access a realm instance (created by a javascript code) by a java native module (react native bridge)?

I've been using realm in my react-native app through javascript API to persist some user data. Now I need to access this realm instance from a native module (react-native bridge in Android) to retrieve this persisted data. Could you tell me how can I do it? I've already installed Realm in my gradle settings, and initiated a default config in MainApplication.java. But I'm getting this error:
io.realm.exceptions.RealmFileException: Directory at path 'data/data/com.moodar/file/default.realm' does not exist
In javascript environment I created a default instance, so I thought I could access this default instance through java interface too.
Here is my overridden onCreate method on MainApplication.java:
super.onCreate();
final int SCHEMA_VERSION = 14;
Realm.init(this);
RealmConfiguration config = new RealmConfiguration
.Builder()
.deleteRealmIfMigrationNeeded()
.schemaVersion(SCHEMA_VERSION)
.build();
Realm.setDefaultConfiguration(config);
...
After reading official documentation I found a solution: Dynamic Realms.
There's no need to create java schemas, you can query objects using Strings.

Is there a c# equivalent of the Python id_token.verify_oauth2_token class and methods

I searched all over the web looking for the C# .NET classes and documentation to allow me to code functional equivalent of this Python method and I can't believe it simply doesn't exist but NuGet hasn't helped and the closest Google documentation I can find is here.
What does exist is classes and examples that show how to authenticate a .NET server or Installable with Google so that it can Access various APIs (Drive etc) but I just want the simple client token Authentication that is referred to for most other languages here
As you will see Python has the google.oauth2.id_token class with its verify_oauth2_token() method and NodeJS and PHP have their verifyIdToken() methods.
Java gets a little more complicated with: -
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
// Specify the CLIENT_ID of the app that accesses the backend:
.setAudience(Collections.singletonList(CLIENT_ID))
// Or, if multiple clients access the backend:
//.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
.build();
// (Receive idTokenString by HTTPS POST)
GoogleIdToken idToken = verifier.verify(idTokenString);
But C# has diddly :-( Please advise!
If it helps I'm implementing a Javascript SSO client. (BTW have no interest in the YOLO library)
I finally found Google C# token verification code on the web. It says it is no longer actively maintained. Why is there no MuGet package? Why is Google making this so hard?
Or just call the Google Validator like Python does?
Also see previous answer Here

Having a fixed response structure with node.js and Express

We have recently started using Node.js for our API server instead of Java. Apart from all the good things which Node.js provides, one thing I miss the most is having a proper response object for an API.
Since Javascript being dynamically typed languages, objects can be created on the fly while returning the response. This is in contrast to Java, where I can have a class , an instance of which will be serialized in the response. I can anytime lookup this class to determine what the response of the API will be.
Is there such a design pattern in Node.Js / Javascript. We would like our API's to have strict conformance to such templated object.
You can make them yourself.
If you're using ES6 for example, you can have various error and response modules, and perform your own validation in the class that creates those responses.
For example,
// sample-response.js
class SampleResponse {
constructor(message) {
// validate `message` somehow
this.data = message
}
}
module.exports = {
SampleResponse
}
Then however you're structuring your HTTP interface, you can send back whichever response you'd like (for example, with Express):
res.send(new SampleResponse(message))
Same goes with errors, etc. You're not necessarily limited by a lack of types with JavaScript, you just have to enforce things differently.
If you're not using ES6, you can do something like this:
module.exports = {
SampleResponse: function(message) {
// do some validation
return { data: message }; // or whatever you want
}
};
You can use Flow or TypeScript for you code.
You can use contract testing tools. Depending on the contract for your REST API:
abao for RAML
dredd for api blueprint
SoapUI for Swagger
My choice is to use TypeScript and Abao+RAML.

Categories

Resources