简体   繁体   中英

Creating API factory with SwaggerJS

So I have this long standing APIService factory that creates functions to pass through the swagger functions to the UI. Here's a snippet of the factory:

'use strict';

angular.module('myApp').factory('APIService', function ($http, $window, $q, swaggerClient, $mdToast) {
    var ApiDoc = {};

    ApiDoc.getAllBookmarks = function () {
        return $q(function (resolve, reject) {
            $http.get('client/components/api/Schema.json')
                    .success(function (data) {
                        var schema = data;
                        _.each(schema.apis, function (b) {
                            b.apiDeclaration.basePath = $window.location.origin;
                        })

                        var api = swaggerClient(schema);
                        api = api.apiBookmarks.getAll();
                        resolve(api);
                     });
        });
    }
    return ApiDoc;
});

And here is a snippet of it's use case in a controller:

$scope.getAllDashboards = function () {
    APIService.getAllBookmarks().then(function(data){
        if (data.length > 0){
           $scope.dashboardsList = data;
           $scope.emptyDash = false;
        } else {
           $scope.emptyDash = true;
        }
    })
}

$scope.getAllDashboards();

The inherent problem herein, is that if I have 30 API function calls in a controller, then there are 30 $http requests for schema.json that are un-needed really. Problem is that I can't figure out how to request/store that json and call on the functions with swagger the same way as they are now (or else I have to change 200+ methods in controllers, urgh). I tried this:

// var api = null;
// $http.get('client/components/api/Schema.json')
//     .success(function (data) {
//         var schema = data;
//         _.each(schema.apis, function (b) {
//             b.apiDeclaration.basePath = $window.location.origin;
//         })
//         api = swaggerClient(schema);
//     });

But couldn't get a function after that to read it properly, or return the result of the function call in a promise like the controllers expect.

I have no other JS developers here so I need help from you all! Thanks much!

That is ugly. If you upgrade your swagger-client to something more modern, you have some options.

First off, you can cache your schema as an object, and supply it in your swaggerClient constructor using the argument spec . You'll still need to pass the URL of the target host to the client when constructing it. With that, there won't need to be any need to call anything remotely.

Next, you can see about keeping a proper swaggerClient instance around, and use it in each of your calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM