Riven/riven/srcgen/endpoints.rs.dt
2024-05-05 23:47:40 -07:00

214 lines
8 KiB
Text

{{
const spec = require('./.spec.json');
const dotUtils = require('./dotUtils.js');
}}{{= dotUtils.preamble() }}
// http://www.mingweisamuel.com/riotapi-schema/tool/
// Version {{= spec.info.version }}
//! Automatically generated endpoint handles.
#![allow(clippy::let_and_return, clippy::too_many_arguments)]
use crate::models::*;
use std::future::Future;
use std::vec::Vec;
#[cfg(feature="tracing")]
use tracing::Instrument;
use reqwest::Method;
use crate::Result;
use crate::consts::{ RegionalRoute, PlatformRoute, ValPlatformRoute };
use crate::riot_api::RiotApi;
{{
const endpointGroups = {};
for (let path of Object.entries(spec.paths)) {
let ep = path[1]['x-endpoint'];
endpointGroups[ep] = endpointGroups[ep] || [];
endpointGroups[ep].push(path);
}
}}
impl RiotApi {
{{
for (const endpointName of Object.keys(endpointGroups)) {
const method = dotUtils.changeCase.snakeCase(endpointName);
const type = dotUtils.changeCase.pascalCase(endpointName);
}}
/// Returns a handle for accessing [{{= type }}](crate::endpoints::{{= type }}) endpoints.
/// # Riot Developer API Reference
/// <a href="https://developer.riotgames.com/apis#{{= endpointName }}" target="_blank">`{{= endpointName }}`</a>
///
/// Note: this method is automatically generated.
#[inline]
pub fn {{= method }}(&self) -> {{= type }} {
{{= type }} { base: self }
}
{{
}
}}
}
{{
for (let [ endpointName, endpointMethods ] of Object.entries(endpointGroups))
{
let endpoint = dotUtils.changeCase.pascalCase(endpointName);
const endpoint_snake_case = dotUtils.changeCase.snakeCase(endpointName);
}}
/// {{= endpoint }} endpoints handle, accessed by calling [`{{= endpoint_snake_case }}()`](crate::RiotApi::{{= endpoint_snake_case }}) on a [`RiotApi`](crate::RiotApi) instance.
/// # Riot Developer API Reference
/// <a href="https://developer.riotgames.com/apis#{{= endpointName }}" target="_blank">`{{= endpointName }}`</a>
///
/// Note: this struct is automatically generated.
#[repr(transparent)]
pub struct {{= endpoint }}<'a> {
base: &'a RiotApi,
}
impl<'a> {{= endpoint }}<'a> {
{{
for (const [ route, path ] of endpointMethods)
{
for (const [ verb, operation ] of Object.entries(path))
{
if (verb.startsWith('x-')) continue;
const operationId = operation.operationId;
const method = dotUtils.changeCase.snakeCase(operationId.slice(operationId.indexOf('.') + 1));
const resp200 = operation.responses['200'];
const isRso = (null != operation.security) && (null != operation.security[0]['rso']);
/* Return type checks. */
let hasReturn = false;
let returnType = '()';
let returnTypeTurbofish = '';
let returnOptional = false;
if (resp200 && resp200.content)
{
hasReturn = true;
const jsonInfo = resp200.content['application/json'];
const parseType = dotUtils.stringifyType(jsonInfo.schema, { endpoint, fullpath: false });
returnTypeTurbofish = `::<${parseType}>`;
returnOptional = !!operation['x-nullable-404'];
returnType = returnOptional ? `Option<${parseType}>` : parseType;
}
/* Body content checks. */
let bodyType = null;
if (operation.requestBody)
{
const jsonInfo = operation.requestBody.content['application/json'];
bodyType = dotUtils.stringifyType(jsonInfo.schema, { endpoint, fullpath: false });
}
/* Description processing. */
let descArr = operation.description.split('\n');
/* Build argument comment & string. */
const argBuilder = [
'route: ', dotUtils.changeCase.pascalCase(operation['x-route-enum']), 'Route'
];
if (isRso) {
argBuilder.push(', access_token: impl std::fmt::Display');
}
/* Add body params before path/query. */
if (bodyType) {
argBuilder.push(', body: &', bodyType);
}
/* Path and query params. */
const allParams = operation.parameters;
let queryParams = [];
let headerParams = [];
let routeArgument;
if (allParams && allParams.length)
{
const pathParams = allParams.filter(p => 'path' === p.in)
.sortBy(({ name }) => route.indexOf(name));
const reqQueryParams = allParams.filter(p => 'query' === p.in && p.required);
const optQueryParams = allParams.filter(p => 'query' === p.in && !p.required)
.sortBy(({ name }) => {
let match = /(^[a-z]+|[A-Z]+(?![a-z])|[A-Z][a-z]+)/.exec(name);
return match.slice(1).reverse().join('');
});
queryParams = reqQueryParams.concat(optQueryParams);
headerParams = allParams.filter(p => 'header' === p.in);
for (let paramList of [ pathParams, reqQueryParams, optQueryParams, headerParams ])
{
const required = paramList === pathParams;
for (const param of paramList)
{
argBuilder.push(', ', dotUtils.normalizePropName(param.name), ': ',
dotUtils.stringifyType(param.schema, { endpoint, optional: !(required || param.required), owned: false }));
}
}
routeArgument = dotUtils.formatRouteArgument(route, pathParams);
}
else
{
routeArgument = dotUtils.formatRouteArgument(route);
}
for (var descLine of descArr)
{
}}
///{{= descLine ? ' ' + descLine : '' }}
{{
}
}}
/// # Parameters
/// * `route` - Route to query.
{{? isRso }}
/// * `access_token` - RSO access token.
{{?}}
{{~ allParams || [] :param }}
/// * `{{= dotUtils.changeCase.snakeCase(param.name) }}` ({{= param.required ? 'required' : 'optional' }}, in {{= param.in }}){{= param.description ? ' - ' + param.description : ''}}
{{~}}
{{? isRso }}
/// # RSO
/// This endpoint uses [Riot Sign On](https://developer.riotgames.com/docs/lol#rso-integration)
/// via the `access_token` parameter, instead of the Riot API key.
{{?}}
/// # Riot Developer API Reference
/// <a href="{{= operation.externalDocs.url }}" target="_blank">`{{= operationId }}`</a>
///
/// Note: this method is automatically generated.
pub fn {{= method }}(&self, {{= argBuilder.join('') }})
-> impl Future<Output = Result<{{= returnType }}>> + 'a
{
let route_str = route.into();
let request = self.base.request(Method::{{= verb.toUpperCase() }}, route_str, {{= routeArgument }});
{{? isRso }}
let mut request = request.bearer_auth(access_token);
if let Some(clear) = self.base.get_rso_clear_header() { request = request.header(clear, "") }
{{?}}
{{~ queryParams :queryParam }}
{{= dotUtils.formatAddQueryParam(queryParam) }}
{{~}}
{{~ headerParams :headerParam }}
{{= dotUtils.formatAddHeaderParam(headerParam) }}
{{~}}
{{? bodyType }}
let request = request.body(serde_json::ser::to_vec(body).unwrap());
{{?}}
let future = self.base.execute{{= hasReturn ? (returnOptional ? '_opt' : '_val') : '' }}{{= returnTypeTurbofish }}("{{= operationId }}", route_str, request);
#[cfg(feature = "tracing")]
let future = future.instrument(tracing::info_span!("{{= operationId }}"));
future
}
{{
}
}
}}
}
{{
}
}}