A function that returns the middleware for a given method and service `getArgs` is a function that should return additional leading service arguments
334175
function getHandler (method, getArgs) {
  return service => {
    return function (req, res, next) {
      const { query } = req;
      const route = omit(req.params, '__feathersId');

      res.setHeader('Allow', allowedMethods(service).join(','));

      // Check if the method exists on the service at all. Send 405 (Method not allowed) if not
      if (typeof service[method] !== 'function') {
        debug(`Method '${method}' not allowed on '${req.url}'`);
        res.status(statusCodes.methodNotAllowed);

        return next(new errors.MethodNotAllowed(`Method \`${method}\` is not supported by this endpoint.`));
      }

      // Grab the service parameters. Use req.feathers
      // and set the query to req.query merged with req.params
      const params = Object.assign({
        query, route
      }, req.feathers);

      Object.defineProperty(params, '__returnHook', {
        value: true
      });

      // Run the getArgs callback, if available, for additional parameters
      const args = getArgs(req, params);

      debug(`REST handler calling \`${method}\` from \`${req.url}\``);

      service[method](...args, true)
        .then(hook => {
          const data = hook.dispatch !== undefined ? hook.dispatch : hook.result;

          res.data = data;
          res.hook = hook;

          if (hook.statusCode) {
            res.status(hook.statusCode);
          } else if (!data) {
            debug(`No content returned for '${req.url}'`);
            res.status(statusCodes.noContent);
          } else if (method === 'create') {
            res.status(statusCodes.created);
          }

          return next();
        })
        .catch(hook => {
          const { error } = hook;

          debug(`Error in handler: \`${error.message}\``);
          res.hook = hook;

          return next(hook.error);
        });
    };
  };
}
791408
def get_action_arguments(self, service_name, action_name):
        
        return self.services[service_name].actions[action_name].info
510901
function templateWithArgs( apiDir, apiName, apiFuncName ) {
	cacheAPIs[apiName] = { 
		reg: (RegularCacheClient
			.replace(/%%api.root%%/g,apiDir)
			.replace(/%%api.name%%/g,apiName)
			.replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName))),
		service: (ServiceCacheClient
			.replace(/%%api.root%%/g,apiDir)
			.replace(/%%api.name%%/g,apiName)
			.replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName)))
	}

}
601723
def map_arg(**maps):
    
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if six.PY2:
                argmap = inspect.getcallargs(func, *args, **kwargs)
            else:
                # getcallargs was deprecated since 3.5
                sig = inspect.signature(func)
                argmap = sig.bind_partial(*args, **kwargs).arguments
            for k, map_func in six.iteritems(maps):
                if k in argmap:
                    argmap[k] = map_func(argmap[k])
            return func(**argmap)
        return wrapper
    return deco
470038
def _replace_services_in_args(self, args):
        
        _check_type('args', args, list)

        new_args = []
        for arg in args:
            if isinstance(arg, list):
                new_args.append(self._replace_services_in_args(arg))
            elif isinstance(arg, dict):
                new_args.append(self._replace_services_in_kwargs(arg))
            elif isinstance(arg, string_types):
                new_args.append(self._replace_service(arg))
            else:
                new_args.append(arg)
        return new_args
1205713
function compose(middleware) {
	const args = [].slice.call(arguments, 1);
  return function *(next) {
    if (!next) next = noop();

    var i = middleware.length;

    while (i--) {
      next = middleware[i].apply(this, args.concat(next));
    }

    return yield *next;
  }
}
1143787
function compose (middleware) {
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  /**
   * @param {Object} context
   * @return {Promise}
   * @api public
   */

  return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}
73896
def wants(cls, *service_names):
        """"""
        def _decorator(cls_):                                # pylint: disable=missing-docstring
            for service_name in service_names:
                cls_._services_requested[service_name] = "want"  # pylint: disable=protected-access
            return cls_
        return _decorator
928787
function sortArgs(method, args) {

		// get the method definition
		var def = _.get(_client.types, method.replace(/\_Task$/i, '') + 'RequestType');
		
		// if found create the definition by calling its function
		if (def) {
			return getFields(def(), args);
		}
		return args;
	}
14685
function middlewareStrategy(metadata, dataAdapter, opts) {
    opts.filter = opts.filter || defaultFilter;
    const { filter } = opts;
    return async function magic(ctx, next) {
        const { name, key } = opts.filter.call(null, ctx);
        const obj = metadata[name];
        const { routeSwitch = {} } = obj;

        let middleware;
        if (routeSwitch[key] === true) {
            const { pres, posts } = getHooks(obj, key);
            const route = routes[key];
            middleware = route.call(null, name, dataAdapter, opts, pres, posts);
        }

        try {
            if (typeof middleware === 'function') {
                await middleware.call(null, ctx, next);
            } else {
                await next();
            }
        } catch (err) {
            throw err;
        }
    }
}
902372
def argument_getter_factory(route_spec):
     
    
    func_sig = inspect.signature(route_spec.handler_func)

    param_names = list(func_sig.parameters.keys())
    arg_getters  = build_argval_getters(route_spec)
    n_args = len(arg_getters)

    async def argument_getters(request):
        errors = None
        values = {}
        for i in range(n_args):
            try:
                arg_name = param_names[i]
                values[arg_name] = await arg_getters[i](request)
            except HTTPException:
                raise
            except Exception as exc :
                if errors is None: 
                    errors = []

                request.app.logger.error('', exc_info=True)

                exc_type = type(exc)

                data = {
                    "name": arg_name, 
                    "type": f"{exc_type.__module__}.{exc_type.__qualname__}",
                    "error": str(exc)
                }

                errors.append(data)

        if errors is not None:
            raise RESTfulArgumentError(errors)

        return values

    return argument_getters
301459
function callApi (method) {
  return function (req, res) {
    var apiAction = api[method](req.guid, req.options)
    handleResponse(apiAction, res)
  }
}
533658
def request(method='GET'):
    

    def decorator(func):
        @functools.wraps(func)
        def action(self, *args, **kwargs):
            f = furl(self.server)
            path, body = func(self, *args, **kwargs)

            # deal with query string
            query = dict()
            if isinstance(path, tuple):
                path, query = path
            f.path.add(path)
            f.query.set(query)

            status_code, result = send_rest(f.url, method=method.upper(),
                                            body=body,
                                            session=self.session,
                                            headers=self.headers)
            if status_code != httplib.OK:
                self.logger.error("{impl} {url} headers: {headers}, code: {code}".format(
                    impl=method, url=f.url, headers=self.headers, code=status_code))
            return status_code, result

        return action

    return decorator
426038
function getHandler (method, getArgs, trans, domain = 'feathers') {
  return function (req, res, next) {
    res.setHeader('Allow', Object.values(allowedMethods).join(','));

    let params = Object.assign({}, req.params || {});
    delete params.service;
    delete params.id;
    delete params.subresources;
    delete params[0];

    req.feathers = { provider: 'rest' };
    // Grab the service parameters. Use req.feathers and set the query to req.query

    let query = req.query || {};
    let headers = fp.dissoc('cookie', req.headers || {});
    let cookies = req.cookies || {};

    params = Object.assign({ query, headers }, params, req.feathers);

    // Transfer the received file
    if (req.file) {
      params.file = req.file;
    }

    // method override
    if ((method === 'update' || method === 'patch')
      && params.query.$method 
      && params.query.$method.toLowerCase() === 'patch') {
      method = 'patch'
      delete params.query.$method
    }

    // Run the getArgs callback, if available, for additional parameters
    const [service, ...args] = getArgs(req, res, next);

    debug(`REST handler calling service \'${service}\'`, {
      cmd: method,
      path: req.path,
      //args: args,
      //params: params,
      //feathers: req.feathers
    });

    // The service success callback which sets res.data or calls next() with the error
    const callback = function (err, data) {
      debug(`${service}.${method} response:`, err || {
        status: data && data.status,
        size: data && JSON.stringify(data).length
      });
      if (err) return next(err.cause || err);

      res.data = data;

      if (!data) {
        debug(`No content returned for '${req.url}'`);
        res.status(statusCodes.noContent);
      } else if (method === 'create') {
        res.status(statusCodes.created);
      }

      return next();
    };

    trans.act({
      topic: `${domain}.${service}`,
      cmd: method,
      path: req.path,
      args: args,
      params: params,
      feathers: req.feathers
    }, callback);
  };
}
1118632
def service(self, *args, **kwargs):
        
        return self._client.service(*args, scope=self.id, **kwargs)
420443
def _GetArgsFromRequest(self, request, method_metadata, route_args):
    """"""
    format_mode = GetRequestFormatMode(request, method_metadata)

    if request.method in ["GET", "HEAD"]:
      if method_metadata.args_type:
        unprocessed_request = request.args
        if hasattr(unprocessed_request, "dict"):
          unprocessed_request = unprocessed_request.dict()

        args = method_metadata.args_type()
        for type_info in args.type_infos:
          if type_info.name in route_args:
            self._SetField(args, type_info, route_args[type_info.name])
          elif type_info.name in unprocessed_request:
            self._SetField(args, type_info, unprocessed_request[type_info.name])

      else:
        args = None
    elif request.method in ["POST", "DELETE", "PATCH"]:
      try:
        args = method_metadata.args_type()
        for type_info in args.type_infos:
          if type_info.name in route_args:
            self._SetField(args, type_info, route_args[type_info.name])

        if request.content_type and request.content_type.startswith(
            "multipart/form-data;"):
          payload = json.Parse(request.form["_params_"].decode("utf-8"))
          args.FromDict(payload)

          for name, fd in iteritems(request.files):
            args.Set(name, fd.read())
        elif format_mode == JsonMode.PROTO3_JSON_MODE:
          # NOTE: Arguments rdfvalue has to be a protobuf-based RDFValue.
          args_proto = args.protobuf()
          json_format.Parse(request.get_data(as_text=True) or "{}", args_proto)
          args.ParseFromString(args_proto.SerializeToString())
        else:
          json_data = request.get_data(as_text=True) or "{}"
          payload = json.Parse(json_data)
          if payload:
            args.FromDict(payload)
      except Exception as e:  # pylint: disable=broad-except
        logging.exception("Error while parsing POST request %s (%s): %s",
                          request.path, request.method, e)
        raise PostRequestParsingError(e)
    else:
      raise UnsupportedHttpMethod("Unsupported method: %s." % request.method)

    return args
34200
def method_wrapper(m):
    """"""

    if m.is_simple:
        def simple_method(self):
            """TODO: no docstring!"""
            return apply_transform(
                self.__service__, m.output_transform,
                grpc_call(self.__service__, m, unwrap(self)))

        return simple_method

    elif m.input_transform is not None:
        def transform_method(self, *args, **kwargs):
            """TODO: no docstring!"""
            request = m.input_transform(self, *args, **kwargs)
            return apply_transform(
                self.__service__, m.output_transform,
                grpc_call(self.__service__, m, request))

        return transform_method

    elif m.static:
        def static_method(cls, *args, **kwargs):
            """TODO: no docstring!"""
            request = make_static_request(m, *args, **kwargs)
            return apply_transform(
                cls.__stub__(__server__), m.output_transform,
                grpc_call(cls.__stub__(__server__), m, request))

        return static_method

    else:
        def request_method(self, *args, **kwargs):
            """TODO: no docstring!"""
            request = make_request(self, m, *args, **kwargs)
            return apply_transform(
                self.__service__, m.output_transform,
                grpc_call(self.__service__, m, request))

        return request_method