Skip to content

feat(typescript-fetch): add docs support #21719

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
protected boolean withoutRuntimeChecks = false;
protected boolean stringEnums = false;
protected String fileNaming = PASCAL_CASE;
protected String apiDocPath = "docs";
protected String modelDocPath = "docs";

// "Saga and Record" mode.
public static final String SAGAS_AND_RECORDS = "sagasAndRecords";
Expand Down Expand Up @@ -107,10 +109,12 @@ public TypeScriptFetchClientCodegen() {
// at the moment
importMapping.clear();

outputFolder = "generated-code/typescript-fetch";
outputFolder = "generated-code" + File.separator + "typescript-fetch";
embeddedTemplateDir = templateDir = "typescript-fetch";

this.apiTemplateFiles.put("apis.mustache", ".ts");
this.apiDocTemplateFiles.put("api_doc.mustache", ".md");
this.modelDocTemplateFiles.put("model_doc.mustache", ".md");

this.addExtraReservedWords();

Expand Down Expand Up @@ -138,6 +142,11 @@ public String toModelFilename(String name) {
return convertUsingFileNamingConvention(super.toModelFilename(name));
}

@Override
public String toModelDocFilename(String name) {
return toModelName(name);
}

/**
* Converts the original name according to the current <code>fileNaming</code> strategy.
*
Expand Down Expand Up @@ -242,6 +251,10 @@ public void processOpts() {
this.apiPackage = sourceDir + "apis";
this.modelPackage = sourceDir + "models";

// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);

supportingFiles.add(new SupportingFile("index.mustache", sourceDir, "index.ts"));
supportingFiles.add(new SupportingFile("runtime.mustache", sourceDir, "runtime.ts"));

Expand Down Expand Up @@ -316,6 +329,16 @@ public void processOpts() {
setGenerateValidationAttributes(convertPropertyToBooleanAndWriteBack(VALIDATION_ATTRIBUTES));
}

@Override
public String apiDocFileFolder() {
return (outputFolder + File.separator + apiDocPath);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...because we seem to be using those constantly here for a local path. If we want to use the constants both in a file path context and a web context we should remove the trailing slash and add it when we use them in a web context.

}

@Override
public String modelDocFileFolder() {
return (outputFolder + File.separator + modelDocPath);
}

@Override
public String toEnumDefaultValue(String value, String datatype) {
if (this.getSagasAndRecords()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,46 +1,127 @@
## {{npmName}}@{{npmVersion}}
# {{npmName}}@{{npmVersion}}

This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments:
A TypeScript SDK client for the {{host}} API.

Environment
* Node.js
* Webpack
* Browserify
## Usage

Language level
* ES5 - you must have a Promises/A+ library installed
* ES6
First, install the SDK from npm.

Module system
* CommonJS
* ES6 module system
```bash
npm install {{npmName}} --save
```

Next, try it out.

{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
```ts
{{>api_example}}
```
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}

## Documentation

### API Endpoints

All URIs are relative to *{{basePath}}*

| Class | Method | HTTP request | Description
| ----- | ------ | ------------ | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}/{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}

### Models

{{#models}}{{#model}}- [{{{classname}}}]({{modelDocPath}}/{{{classname}}}.md){{/model}}
{{/models}}

### Authorization

{{^authMethods}}Endpoints do not require authorization.{{/authMethods}}
{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}}
{{#authMethods}}
<a id="{{name}}{{#isOAuth}}-{{flow}}{{/isOAuth}}"></a>
#### {{name}}{{#isOAuth}} {{flow}}{{/isOAuth}}

{{#isApiKey}}

- **Type**: API key
- **API key parameter name**: `{{keyParamName}}`
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasicBasic}}

- **Type**: HTTP basic authentication
{{/isBasicBasic}}
{{#isBasicBearer}}

- **Type**: HTTP Bearer Token authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}
{{/isBasicBearer}}
{{#isHttpSignature}}

It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html))
- **Type**: HTTP signature authentication
{{/isHttpSignature}}
{{#isOAuth}}

- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - `{{scope}}`: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}

## About

This TypeScript SDK client supports the [Fetch API](https://fetch.spec.whatwg.org/)
and is automatically generated by the
[OpenAPI Generator](https://openapi-generator.tech) project:

- API version: `{{appVersion}}`
- Package version: `{{npmVersion}}`
{{^hideGenerationTimestamp}}
- Build date: `{{generatedDate}}`
{{/hideGenerationTimestamp}}
- Generator version: `{{generatorVersion}}`
- Build package: `{{generatorClass}}`

The generated npm module supports the following:

- Environments
* Node.js
* Webpack
* Browserify
- Language levels
* ES5 - you must have a Promises/A+ library installed
* ES6
- Module systems
* CommonJS
* ES6 module system

{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}

## Development

### Building

To build and compile the typescript sources to javascript use:
```
To build the TypeScript source code, you need to have Node.js and npm installed.
After cloning the repository, navigate to the project directory and run:

```bash
npm install
npm run build
```

### Publishing

First build the package then run `npm publish`

### Consuming

navigate to the folder of your consuming project and run one of the following commands.
Once you've built the package, you can publish it to npm:

_published:_

```
npm install {{npmName}}@{{npmVersion}} --save
```bash
npm publish
```

_unPublished (not recommended):_
## License

```
npm install PATH_TO_GENERATED_PACKAGE --save
```
[{{licenseInfo}}]({{{licenseUrl}}})
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# {{classname}}{{#description}}

{{.}}{{/description}}

All URIs are relative to *{{basePath}}*

| Method | HTTP request | Description |
|------------- | ------------- | -------------|
{{#operations}}{{#operation}}| [**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{commonPath}}{{path}} | {{summary}} |
{{/operation}}{{/operations}}

{{#operations}}
{{#operation}}

## {{operationId}}

> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}})

{{summary}}{{#notes}}

{{.}}{{/notes}}

### Example

```ts
{{>api_example}}
```

### Parameters

{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|{{/-last}}{{/allParams}}
{{#allParams}}| **{{paramName}}** | {{#isEnum}}{{#allowableValues}}{{#values}}`{{{.}}}`{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}{{/isEnum}}{{^isEnum}}{{#isModel}}[{{baseType}}]({{baseType}}.md){{/isModel}}{{^isModel}}`{{{dataType}}}`{{/isModel}}{{/isEnum}} | {{description}} |{{^required}} [Optional]{{/required}}{{^isContainer}}{{#defaultValue}} [Defaults to `{{.}}`]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [Enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} |
{{/allParams}}

### Return type

{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}`void` (Empty response body){{/returnType}}

### Authorization

{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}{{#isOAuth}} {{flow}}{{/isOAuth}}](../README.md#{{{name}}}{{#isOAuth}}-{{flow}}{{/isOAuth}}){{^-last}}, {{/-last}}{{/authMethods}}

### HTTP request headers

- **Content-Type**: {{#consumes}}`{{{mediaType}}}`{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}`{{{mediaType}}}`{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}}

{{#responses.0}}

### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
{{#responses}}
| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} |
{{/responses}}
{{/responses.0}}

[[Back to top]](#) [[Back to API list]](../README.md#api-endpoints) [[Back to Model list]](../README.md#models) [[Back to README]](../README.md)

{{/operation}}
{{/operations}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
Configuration,
{{classname}},
} from '{{npmName}}';
import type { {{operationIdCamelCase}}Request } from '{{npmName}}';

async function example() {
console.log("🚀 Testing {{npmName}} SDK...");
{{#hasAuthMethods}}
const config = new Configuration({ {{#authMethods}}{{#isBasicBasic}}
// To configure HTTP basic authorization: {{{name}}}
username: "YOUR USERNAME",
password: "YOUR PASSWORD",{{/isBasicBasic}}{{#isBasicBearer}}
// Configure HTTP bearer authorization: {{{name}}}
accessToken: "YOUR BEARER TOKEN",{{/isBasicBearer}}{{#isOAuth}}
// To configure OAuth2 access token for authorization: {{{name}}} {{{flow}}}
accessToken: "YOUR ACCESS TOKEN",{{/isOAuth}}{{#isApiKey}}
// To configure API key authorization: {{{name}}}
apiKey: "YOUR API KEY",{{/isApiKey}}{{#isHttpSignature}}
// To configure HTTP signature authorization: {{{name}}}
headers: { "YOUR HEADER NAME": "YOUR SIGNATURE" },{{/isHttpSignature}}{{/authMethods}}
});
{{/hasAuthMethods}}
const api = new {{classname}}({{#hasAuthMethods}}config{{/hasAuthMethods}});

{{#hasParams}}
const body = {
{{#allParams}}
// {{{dataType}}}{{#description}} | {{{description}}}{{/description}}{{^required}} (optional){{/required}}
{{paramName}}: {{{example}}}{{^example}}...{{/example}},
{{/allParams}}
} satisfies {{operationIdCamelCase}}Request;

{{/hasParams}}
try {
const data = await api.{{{operationId}}}({{#hasParams}}body{{/hasParams}});
console.log(data);
} catch (error) {
console.error(error);
}
}

// Run the test
example().catch(console.error);
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{{#models}}{{#model}}
# {{classname}}

{{#description}}{{&description}}
{{/description}}

## Properties

Name | Type
------------ | -------------
{{#vars}}`{{name}}` | {{#isPrimitiveType}}{{dataType}}{{/isPrimitiveType}}{{^isPrimitiveType}}[{{dataType}}]({{complexType}}.md){{/isPrimitiveType}}
{{/vars}}

{{^withoutRuntimeChecks}}
## Example

```typescript
import type { {{classname}} } from '{{npmName}}'

// TODO: Update the object below with actual values
const example = {
{{#vars}}
"{{name}}": {{{example}}},
{{/vars}}
} satisfies {{classname}}

console.log(example)

// Convert the instance to a JSON string
const exampleJSON: string = JSON.stringify(example)
console.log(exampleJSON)

// Parse the JSON string back to an object
const exampleParsed = JSON.parse(exampleJSON) as {{classname}}
console.log(exampleParsed)
```
{{/withoutRuntimeChecks}}

[[Back to top]](#) [[Back to API list]](../README.md#api-endpoints) [[Back to Model list]](../README.md#models) [[Back to README]](../README.md)

{{/model}}{{/models}}
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
docs/AbstractUserDto.md
docs/BranchDto.md
docs/InternalAuthenticatedUserDto.md
docs/RemoteAuthenticatedUserDto.md
index.ts
models/AbstractUserDto.ts
models/BranchDto.ts
Expand Down
Loading