server.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); 
启动命令
772391
function runCmd(cmd, args, fn) {
    args = args || [];
    let runner = require('child_process').spawn(cmd, args, {
        // keep color
        stdio: 'inherit',
    });
    runner.on('close', function(code) {
        if (fn) {
            fn(code);
        }
    });
}
330457
function processServices(swagger, models, options) {
  var param, name, i, j;
  var services = {};
  var minParamsForContainer = options.minParamsForContainer || 2;
  var sortParams = options.sortParams || 'desc';
  for (var url in swagger.paths) {
    var path = swagger.paths[url];
	  var methodParameters = path.parameters;
    for (var method in path || {}) {
      var def = path[method];
      if (!def || method == 'parameters') {
        continue;
      }
      var tags = def.tags || [];
      var tag = tagName(tags.length == 0 ? null : tags[0], options);
      var descriptor = services[tag];
      if (descriptor == null) {
        var serviceClass = toClassName(tag);
        descriptor = {
          serviceName: tag,
          serviceClass: serviceClass + 'Service',
          serviceFile: toFileName(serviceClass) + '.service',
          operationIds: new Set(),
          serviceOperations: [],
        };
        services[tag] = descriptor;
      }

      var id = operationId(
        def.operationId,
        method,
        url,
        descriptor.operationIds
      );

      var parameters = def.parameters || [];

      if (methodParameters) {
        parameters = parameters.concat(methodParameters);
      }

      var paramsClass = null;
      var paramsClassComments = null;
      if (parameters.length >= minParamsForContainer) {
        paramsClass = id.charAt(0).toUpperCase() + id.substr(1) + 'Params';
        paramsClassComments = toComments('Parameters for ' + id, 1);
      }

      var operationParameters = [];
      for (var p = 0; p < parameters.length; p++) {
        param = parameters[p];
        if (param.$ref) {
          param = resolveRef(swagger, param.$ref);
        }
        var paramType;
        if (param.schema) {
          paramType = propertyType(param.schema);
        } else {
          paramType = propertyType(param);
        }
        var paramTypeNoNull = removeBrackets(paramType, true);
        var paramVar = toIdentifier(param.name);
        var paramDescriptor = {
          paramName: param.name,
          paramIn: param.in,
          paramVar: paramVar,
          paramFullVar: (paramsClass == null ? '' : 'params.') + paramVar,
          paramRequired: param.required === true || param.in === 'path',
          paramIsQuery: param.in === 'query',
          paramIsPath: param.in === 'path',
          paramIsHeader: param.in === 'header',
          paramIsBody: param.in === 'body',
          paramIsFormData: param.in === 'formData',
          paramIsArray: param.type === 'array',
          paramToJson: param.in === 'formData' && paramTypeNoNull !== 'Blob' &&
            paramTypeNoNull !== 'string',
          paramDescription: param.description,
          paramComments: toComments(param.description, 2),
          paramType: paramType,
          paramCollectionFormat: param.collectionFormat,
        };
        operationParameters.push(paramDescriptor);
      }
      operationParameters.sort((a, b) => {
        if (a.paramRequired && !b.paramRequired) return -1;
        if (!a.paramRequired && b.paramRequired) return 1;
        switch (sortParams) {
          case 'asc':
            return a.paramName > b.paramName ? 1 :
              a.paramName < b.paramName ? -1 : 0;
          case 'desc':
            return a.paramName > b.paramName ? -1 :
              a.paramName < b.paramName ? 1 : 0;
          default:
            return 0;
        }
      });
      if (operationParameters.length > 0) {
        operationParameters[operationParameters.length - 1].paramIsLast = true;
      }
      var operationResponses = processResponses(swagger, def, path, models);
      var resultType = operationResponses.resultType;
      var isMultipart = false;
      for (i = 0; i < operationParameters.length; i++) {
        if (operationParameters[i].paramIsFormData) {
          isMultipart = true;
          break;
        }
      }
      var docString = (def.description || '').trim();
      if (paramsClass == null) {
        for (i = 0; i < operationParameters.length; i++) {
          param = operationParameters[i];
          docString +=
            '\n@param ' + param.paramName + ' ' + param.paramDescription;
        }
      } else {
        docString +=
          '\n@param params The `' +
          descriptor.serviceClass +
          '.' +
          paramsClass +
          '` containing the following parameters:\n';
        for (i = 0; i < operationParameters.length; i++) {
          param = operationParameters[i];
          docString += '\n- `' + param.paramName + '`: ';
          var lines = (param.paramDescription || '').trim().split('\n');
          for (var l = 0; l < lines.length; l++) {
            var line = lines[l];
            if (line === '') {
              docString += '\n';
            } else {
              docString += (l == 0 ? '' : '  ') + line + '\n';
            }
          }
        }
      }
      if (operationResponses.resultDescription) {
        docString += '\n@return ' + operationResponses.resultDescription;
      }
      function getOperationName(string) {
        if (options.camelCase) return string.charAt(0).toLowerCase() + string.slice(1);
        else return string;
      }
      var operation = {
        operationName: getOperationName(id),
        operationParamsClass: paramsClass,
        operationParamsClassComments: paramsClassComments,
        operationMethod: method.toLocaleUpperCase(),
        operationPath: url,
        operationPathExpression:
          toPathExpression(operationParameters, paramsClass, url),
        operationResultType: resultType,
        operationHttpResponseType: '__StrictHttpResponse<' + resultType + '>',
        operationComments: toComments(docString, 1),
        operationParameters: operationParameters,
        operationResponses: operationResponses,
      };
      var modelResult = models[removeBrackets(resultType)];
      var actualType = resultType;
      if (modelResult && modelResult.modelIsSimple) {
        actualType = modelResult.modelSimpleType;
      }
      operation.operationIsMultipart = isMultipart;
      operation.operationIsVoid = actualType === 'void';
      operation.operationIsString = actualType === 'string';
      operation.operationIsNumber = actualType === 'number';
      operation.operationIsOther =
        !['void', 'number', 'boolean'].includes(actualType);
      operation.operationIsBoolean = actualType === 'boolean';
      operation.operationIsEnum = modelResult && modelResult.modelIsEnum;
      operation.operationIsObject = modelResult && modelResult.modelIsObject;
      operation.operationIsPrimitiveArray =
        !modelResult && (resultType.toString().includes('Array<') ||
          resultType.toString().includes('[]'));
      operation.operationIsFile = actualType === 'Blob';
      operation.operationResponseType =
        operation.operationIsFile ? 'blob' :
        operation.operationIsVoid ||
        operation.operationIsString ||
        operation.operationIsNumber ||
        operation.operationIsBoolean ||
        operation.operationIsEnum ?
          'text' : 'json';
      operation.operationIsUnknown = !(
        operation.operationIsVoid ||
        operation.operationIsString ||
        operation.operationIsNumber ||
        operation.operationIsBoolean ||
        operation.operationIsEnum ||
        operation.operationIsObject ||
        operation.operationIsFile ||
        operation.operationIsPrimitiveArray
      );
      descriptor.serviceOperations.push(operation);
    }
  }

  // Read the comments of each tag to use for service comments
  if (swagger.tags && swagger.tags.length > 0) {
    for (i = 0; i < swagger.tags.length; i++) {
      const tag = swagger.tags[i];
      const name = tagName(tag.name);
      const service = services[name];
      if (service && tag.description) {
        service.serviceComments = toComments(tag.description);
      }
    }
  }

  // Resolve the models used by each service
  for (name in services) {
    var service = services[name];
    var dependencies = new DependenciesResolver(models);
    var errorDependencies = new DependenciesResolver(models);
    for (i = 0; i < service.serviceOperations.length; i++) {
      var op = service.serviceOperations[i];
      for (var code in op.operationResponses) {
        var status = Number(code);
        var actualDeps = (status < 200 || status >= 300)
          ? errorDependencies : dependencies;
        var response = op.operationResponses[code];
        if (response.type) {
          var type = response.type;
          if (type && type.allTypes) {
            // This is an inline object. Append all types
            type.allTypes.forEach(t => actualDeps.add(t));
          } else {
            actualDeps.add(type);
          }
        }
      }
      for (j = 0; j < op.operationParameters.length; j++) {
        param = op.operationParameters[j];
        dependencies.add(param.paramType);
      }
    }
    service.serviceDependencies = dependencies.get();
    service.serviceErrorDependencies = errorDependencies.get();
  }

  return services;
}
516035
def add_swagger(app, json_route, html_route, **kwargs):
    
    app.route(json_route)(create_swagger_json_handler(app, **kwargs))
    add_swagger_api_route(app, html_route, json_route)
206992
function appendApidocRoute(routeConfig, renderApiDoc, groupMockConfig) {
    routeConfig['GET /_apidoc'] = function(request, response, next) {
        // /_apidoc 也做为一个接口来提供(使用 CORS 方式), 这样更加便于自定义 _apidoc 的 UI.
        // 完全支持自己写一套 UI 来获取解析 /_apidoc 提供的 JSON 数据来展现接口文档
        // 提供了默认的 example/_apidoc.html 做为默认的接口文档实现
        mockRoute.enableCors(request, response);

        if (renderApiDoc) {
            response.send(renderApiDoc(groupMockConfig));
        } else {
            response.jsonp(groupMockConfig);
        }
    };
}
1206613
function getOriginApi(apiMap, apiName) {
    // 如果为全局mock模式，则直接修改apiName对应的mock路径，例如：
    // http://127.0.0.1:3000/__MOCK__/blog/blogApi
    if (config.isFullMock) {
      return `${config.mockPath}/${apiName}/`
    } else {
      const originApi = apiMap[apiName];

      // 如果在api配置中查找不到对应的api则报错
      if (!originApi) {
        throw `Undefined proxy url：${path} , please check your api config!`;
      }

      // 对于路由结尾强制添加"/"
      return originApi.replace(/([^\/])$/,'$1/');
    }


  }
527160
def serve_doc(app, url):
    
    @app.route(url, doc=False)
    def index(env, req):
        ret = ''
        for d in env['doc']:
            ret += 'URL: {url}, supported methods: {methods}{doc}\n'.format(**d)
        return ret
944448
function init(app, context, swagger) {
        logger.log('debug', '%s|adding|routes|context=%s', meta.module, context, meta);
        if (swagger) {
            describeModels(swagger);
            swagger.addPost({
                'spec': {
                    "path" : context + format + '/lex/phrase', 
                    "notes" : "To use only the lexer to tokenize a phrase. The output of the lexer can be pass directly to the tokenizer.",
                    "method": "POST",
                    "summary" : "Split a phrase into tokens.",
                    "nickname" : "lexer",
                    "responseClass" : "Tokens",
                    "params" : [
                        swagger.params.post("phrase", "A phrase to be tokenized", '{"phrase":"Hello world"}'),
                    ],
                    "errorResponses" : [
                        swagger.errors.notFound('phrase'),
                        swagger.errors.invalid('phrase')
                    ]
                },
                'action': function(req, res) {
                    if (!req.body)
                        throw swagger.error(400, 'Missing body of the request');
                    if (!req.body.phrase)
                        throw swagger.error(400, 'Missing the "phrase" in the body of the request');
                    pos.rest.lexPhrase(req, res);
                }
            }).addPost({
                'spec': {
                    "path" : context + format + '/tag/words',
                    "notes" : "To use the tagger on a list of tokens.",
                    "method": "POST",
                    "summary" : "Tag each tokenized word.",
                    "nickname" : "word-tagger",
                    "responseClass" : "Tags",
                    "params" : [
                        swagger.params.post("words", "A list of tokenized words to be tagged", '{"words":["hello","world"]}'),
                    ],
                    "errorResponses" : [
                        swagger.errors.notFound('words'),
                        swagger.errors.invalid('words')
                    ]
                },
                'action': function(req, res) {
                    if (!req.body)
                        throw swagger.error(400, 'Missing body of the request');
                    if (!req.body.words)
                        throw swagger.error(400, 'Missing the "words" array in the body of the request');
                    pos.rest.tagWords(req, res);
                }
            }).addPost({
                'spec': {
                    "path" : context + format + '/tag/phrase',
                    "notes" : "Use the lexer on the phrase and, tag the resulting tokens.",
                    "method": "POST",
                    "summary" : "Tokenize a phrase and then tag each token.",
                    "nickname" : "tagger",
                    "responseClass" : "Tags",
                    "params" : [
                        swagger.params.post("phrase", "A phrase to be tokenized and tagged", '{"phrase":"Hello world"}'),
                    ],
                    "errorResponses" : [
                        swagger.errors.notFound('phrase'),
                        swagger.errors.invalid('phrase')
                    ]
                },
                'action': function(req, res) {
                    if (!req.body)
                        throw swagger.error(400, 'Missing body of the request');
                    if (!req.body.phrase)
                        throw swagger.error(400, 'Missing the "phrase" in the body of the request');
                    pos.rest.tagPhrase(req, res);
                }
            });
        } else {
            router.add(app, context + '/pos.json/lex/phrase', 'POST', pos.rest.lexPhrase);
            router.add(app, context + '/pos.json/tag/words',  'POST', pos.rest.tagWords);
            router.add(app, context + '/pos.json/tag/phrase', 'POST', pos.rest.tagPhrase);
        }
    }
174674
function createServer () {

    // Create server

    var server = express.createServer();

    // Configure Server

    server.configure(function () {

        // Built-in

        server.use(express.methodOverride());                           // Allow method override using _method form parameter
        server.use(express.bodyDecoder()); 	                            // Parse application/x-www-form-urlencoded
        server.use(express.staticProvider(__dirname + '/files'));       // Serve client documents in local directory

        // Local

        server.use(setResponseHeader());                                // Set default response headers for CORS
        server.use(logConsole());                                       // Display incoming requests

        // Authentication

        server.use(auth([auth.Mac({ realm: "Example",                   // Set realm, typically a domain name or application name
                                    getTokenAttributes: getToken,       // Function used to fetch the access token record, typically from a database
                                    // hostHeader: 'x-forwarded-host',  // Needed when running behind a proxy such as Apache2
                                    // isHTTPS: true,                   // Uncomment for HTTPS
                                    checkNonce: nonceCheck,             // Optional nonce checking function
                                    bodyHashMode: "require" })]));      // Require body hash validation for all non GET/HEAD/OPTIONS requests
    });

    // Setup generic OPTIONS route

    server.options(/.+/, function (req, res) {

        res.send(' ');
    });

    return server;
}
14033
function(apiId, swaggerPath) {
        return new Promise(function(resolve, reject) {
            fs.readFile(swaggerPath, function(err, data) {
                if (err) return reject(err);
                
                resolve(APIG.putRestApi({
                    restApiId: apiId,
                    body: data,
                    mode: 'overwrite'
                }).promise());
            });
        });
    }
363515
function loadAPI() {
  var apiPath = this.fullPath(this.paths.api);
  if (fs.existsSync(apiPath) && fs.statSync(apiPath).isDirectory()) {
    var files = protos.util.ls(apiPath, this.regex.jsFile);
    files.forEach(function(file) {
      var methods = protos.require(apiPath + "/" + file, true); // Don't use module cache (allow reloading)
      _.extend(this.api, methods);
    }, this);
  }
  this.emit('api_loaded', this.api);
}
978483
def add_swagger(app, json_route, html_route):
    
    app.router.add_route('GET', json_route, create_swagger_json_handler(app))
    add_swagger_api_route(app, html_route, json_route)
170922
function Handlers(server) {
  var self = this;
  this.server = server;

  //Store the most recently parsed swagger data for when only the handlers get re-attached.
  this.server.on('parsed', function(err, api, parser, basePath) {
    self.api = api;
    self.parser = parser;
    self.basePath = basePath;
    self.setupHandlers();
  });
}
686762
function (hostId) {

        var swaggerDocResult = {};
        var registeredServices = Shared.registeredServices();
        var bodySchemaCounter = 0;
        var bodySchemaModels = [];
        var pathArray = [];

        registeredServices = registeredServices.sort(function (a, b) {
            var x = a["name"];
            var y = b["name"];
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });

        for (var index in registeredServices) {
            var service = registeredServices[index];
            var responses = service.responses;
            if (service.docs == true && service.hostId == hostId && service.url.match(/^\//)) {
                var parameters = service.parameters;
                var responseSchemes = {};
                if (!_.isEmpty(responses)) {


                    // Build swagger compatible parameters definition
                    var swaggerParameters = [];

                    if (!_.isEmpty(parameters)) {
                        for (var sectionName in parameters) {
                            var section = parameters[sectionName];
                            var parameterName;
                            if (sectionName != "body") {
                                var swaggerParameter = {};
                                var parameter;
                                for (parameterName in section) {

                                    parameter = section[parameterName];

                                    // Skip parameters which should not be shown in the documentation
                                    if (_.get(parameter, 'docs') === false) continue;

                                    var type = parameter.type ? parameter.type.toLowerCase() : "string";
                                    if (type != "string" && type != "number" && type != "boolean" && type != "array") {
                                        type = "string";
                                    }

                                    swaggerParameter = {
                                        "in": sectionName,
                                        "name": parameterName,
                                        "type": type,
                                        "description": parameter.desc || "",
                                        "required": parameter.required || false
                                    };
                                    swaggerParameters.push(swaggerParameter);
                                }
                            } else {

                                var thisHash = "def-" + ObjectHash(parameters[sectionName]);
                                var subSchemaObject = _createBodySchema(bodySchemaModels, parameters[sectionName]);
                                bodySchemaModels = subSchemaObject.bodySchemaModels;

                                _registeredSchemaDefs[thisHash] = true;
                                swaggerParameters.push({
                                    "in": "body",
                                    "name": "body",
                                    schema: {
                                        "$ref": "#/definitions/" + thisHash
                                    }
                                });

                                bodySchemaCounter++;
                            }
                        }
                    }

                    // Build swagger compatible response definition
                    var responseCodes = {};
                    var successHash = null;
                    var errorHash = null;

                    if (!_.isEmpty(service.responseSchemes)) {
                        if (service.responseSchemes.success) {
                            successHash = "def-" + ObjectHash(service.responseSchemes.success);
                            var subSchemaObjectSuccess = _createBodySchema(bodySchemaModels, service.responseSchemes.success);
                            bodySchemaModels = subSchemaObjectSuccess.bodySchemaModels;
                        }
                        if (service.responseSchemes.error) {
                            errorHash = "def-" + ObjectHash(service.responseSchemes.error);
                            var subSchemaObjectError = _createBodySchema(bodySchemaModels, service.responseSchemes.error);
                            bodySchemaModels = subSchemaObjectError.bodySchemaModels;
                        }
                    }

                    for (var responseCode in responses) {
                        if (parseInt(responseCode) == 204) {
                            responseCodes[responseCode] = {
                                "description": responses[responseCode].join(', ')
                            }
                        }
                        else {
                            if (parseInt(responseCode) < 300) {
                                if (successHash) {
                                    _registeredSchemaDefs[successHash] = true;
                                    responseCodes[responseCode] = {
                                        "description": responses[responseCode].join(', '),
                                        "schema": {
                                            "$ref": "#/definitions/" + successHash
                                        }
                                    }
                                }
                                else {
                                    responseCodes[responseCode] = {
                                        "description": responses[responseCode].join(', '),
                                        "schema": {
                                            "$ref": "#/definitions/Success"
                                        }
                                    }
                                }
                            }
                            else {
                                if (errorHash) {
                                    _registeredSchemaDefs[errorHash] = true;
                                    responseCodes[responseCode] = {
                                        "description": responses[responseCode].join(', '),
                                        "schema": {
                                            "$ref": "#/definitions/" + errorHash
                                        }
                                    }
                                }
                                else {
                                    responseCodes[responseCode] = {
                                        "description": responses[responseCode].join(', '),
                                        "schema": {
                                            "$ref": "#/definitions/Error"
                                        }
                                    }
                                }
                            }
                        }
                    }

                    var swaggerDoc = {
                        "description": service.description || "",
                        "responses": responseCodes
                    };

                    if (service.deprecated === true) {
                        swaggerDoc.description = "NOTICE: THIS SERVICE IS DEPRECATED\n" + swaggerDoc.description;
                    }

                    if (!_.isEmpty(swaggerParameters)) {
                        swaggerDoc.parameters = swaggerParameters;
                    }

                    //add swagger docu, if present
                    var swaggerPath = service.url.replace(/:(\w)+/ig, function (match) {

                        swaggerDoc.parameters = swaggerDoc.parameters || [];
                        var pathVaribleIsDefined = false;
                        for (var pIndex in swaggerParameters) {
                            if (swaggerParameters[pIndex].in == "path" && swaggerParameters[pIndex].name == match.substring(1)) {
                                pathVaribleIsDefined = true
                            }
                        }
                        if (pathVaribleIsDefined == false) {
                            swaggerDoc.parameters.push({
                                "in": "path",
                                "name": match.substring(1),
                                "description": match.substring(1),
                                "required": true,
                                "type": "string"
                            });
                        }

                        return '{' + match.substring(1) + '}';
                    });

                    var env = Shared.config("environment");

                    if (_.isEmpty(swaggerDocResult)) {
                        swaggerDocResult = {};
                        swaggerDocResult["swagger"] = "2.0";
                        swaggerDocResult["info"] = {
                            "title": env.title || "API",
                            "description": env.description || "API documentation",
                            "version": env.version || "1.0"
                        };
                        //swaggerDocResult["host"] = "localhost:3000";
                        swaggerDocResult["basePath"] = "/";
                        swaggerDocResult["produces"] = ["application/json"];
                        swaggerDocResult["definitions"] = {
                            "ServiceDescriptions": {
                                "properties": {
                                    "status": {
                                        "type": "number"
                                    },
                                    response: {
                                        "type": "array",
                                        "items": {
                                            "$ref": "#/definitions/ServiceDescription"
                                        }
                                    }
                                }
                            },
                            "ServiceDescription": {
                                "properties": {
                                    "modified": {
                                        "type": "string"
                                    },
                                    "url": {
                                        "type": "string"
                                    },
                                    "authorization": {
                                        "type": "boolean"
                                    },
                                    "name": {
                                        "type": "string"
                                    },
                                    "requestMethods": {
                                        "type": "array",
                                        "items": {
                                            "type": "string"
                                        }
                                    }
                                }
                            },
                            "Error": {
                                "properties": {
                                    "status": {
                                        type: "number"
                                    },
                                    "errors": {
                                        "type": "array",
                                        "items": {
                                            "$ref": "#/definitions/ErrorDescription"
                                        }
                                    }
                                }
                            },
                            "ErrorDescription": {
                                "properties": {
                                    "code": {
                                        "type": "string"
                                    },
                                    "msg": {
                                        "type": "string"
                                    }
                                }
                            },
                            "Success": {
                                "properties": {
                                    "status": {
                                        "type": "number"
                                    },
                                    response: {}

                                }
                            }
                        };
                        var env = Shared.config('environment');
                        if (env.swagger) {
                            swaggerDocResult = _.merge(swaggerDocResult, _.cloneDeep(Shared.config('environment.swagger')));
                        }
                    }

                    //Register body schema models
                    for (var sIndex in bodySchemaModels) {
                        if (_registeredSchemaDefs[bodySchemaModels[sIndex].name]) {
                            swaggerDocResult.definitions[bodySchemaModels[sIndex].name] = bodySchemaModels[sIndex].schema;
                        }
                    }

                    for (var rSIndex in responseSchemes) {
                        //swaggerDocResult.definitions[rSIndex] = responseSchemes[rSIndex];
                    }

                    swaggerDocResult.paths = swaggerDocResult.paths || {};

                    var data = swaggerDoc;

                    if (service.deprecated === true) {
                        data.tags = [service.name + " (deprecated)"];
                    }
                    else {
                        data.tags = [service.name];
                    }

                    pathArray.push({
                        name: (service.name + swaggerPath + service.requestMethod.toLowerCase()).replace(/[^a-zA-Z0-9]+/g, ""),
                        requestMethod: service.requestMethod.toLowerCase(),
                        path: swaggerPath,
                        data: data
                    });
                }
            }
        }


        if (!_.isEmpty(pathArray)) {
            swaggerDocResult.paths = swaggerDocResult.paths || {};
            pathArray = pathArray.sort(function (a, b) {
                var x = a["name"];
                var y = b["name"];
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            });

            for (var index in pathArray) {
                var path = pathArray[index]["path"];
                swaggerDocResult.paths[path] = swaggerDocResult.paths[path] || {};
                swaggerDocResult.paths[path][pathArray[index]["requestMethod"]] = pathArray[index]["data"]
            }
        }

        return swaggerDocResult;

    }
897685
function executeApi(apiName, opts, extras){

  var emitter = new Emitter()
    , apiItem
    , token = opts.access_token
    , form, method, path
    , url
    ;
  
  if(/^(https?:\/\/|\/)/.test(apiName)){
    if(apiName.indexOf('/') === 0){
      url = api.HOST + apiName;
    }else{
      url = apiName;
    }
    extras = extras || {};
    method = extras.method;
    
  }else{
    apiItem = getApiItem(apiName);
    if(!apiItem){
      process.nextTick(function(){
        emitter.emit('error', 'no or not support api: ' + apiName);
      });
      return emitter;
    }
    
    path = apiItem.path;
    method = apiItem.method;
    
    url = api.HOST + api.PREPATH + path + '.json';
  }
  
  if(method == 'post'){
    form = opts;
    opts = {};
  }
  
  delete opts.access_token;
  
  request({
      url: url + '?access_token=' + token
    , method: method
    , qs: opts
    , form: form
  }, function(err, res, reply){
    if(err){
      emitter.emit('error', err);
    }else{
      try{
        reply = JSON.parse(reply);
        emitter.emit('success', reply);
      }catch(e){
        emitter.emit('error', reply);
      }
    }
  });
  
  return emitter;
}
507711
function API(opts) {
  opts = opts || {};

  this.verbose = !!opts.verbose;
  this.request = opts.request || request;
  this.baseUrl = opts.baseUrl || BASE_URL;
  var parsedUrl = url.parse(this.baseUrl);
  this.basePath = parsedUrl.path;
  this.baseHost = parsedUrl.protocol + '//' + parsedUrl.host;
  this.timeout = opts.timeout || 50000;

  if (this.verbose) {
    log.setLevel('debug');
  } else {
    log.setLevel('info');
  }
}
407074
function RestAPI() {
  this.models = {};
  this.router = express.Router();
  this.router.use(require('res-error')({
    log: false
  }));
}
852254
def create_swagger_json_handler(app, **kwargs):
    

    spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    def swagger():
        return Response(
            encoded_spec,
            # we allow CORS, so this can be requested at swagger.io
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger