Skip to content

Commit

Permalink
feat: new template for xior
Browse files Browse the repository at this point in the history
chore: update libraries
  • Loading branch information
yhnavein committed Jun 2, 2024
1 parent 104da7e commit cba4f9a
Show file tree
Hide file tree
Showing 11 changed files with 654 additions and 77 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ The following templates are bundled with Swaggie:

```
axios Default template. Recommended for React / Vue / similar frameworks. Uses axios
xior Lightweight and modern alternative to axios. Uses [xior](https://github.com/suhaotian/xior#intro)
swr-axios Template that embraces SRW for GET requests and as a fallback uses axios.
fetch Template similar to axios, but with fetch API instead. Recommended for React / Vue / similar frameworks
ng1 Template for Angular 1 (this is for the old one)
Expand Down Expand Up @@ -126,7 +127,7 @@ Let's assume that you have a [PetStore API](http://petstore.swagger.io/) as your

Instead of writing any code by hand for fetching particular resources, we will let Swaggie do it for us.

> Please note that it's **recommended** to pipe Swaggie command to some prettifier like `prettier` or `dprint` to make the generated code look not only nice, but also persistent.
> Please note that it's **recommended** to pipe Swaggie command to some prettifier like `prettier`, `biome` or `dprint` to make the generated code look not only nice, but also persistent.
> Because Swaggie relies on a templating engine, whitespaces are generally a mess, so they may change between versions.
### Suggested prettiers
Expand All @@ -137,10 +138,10 @@ Instead of writing any code by hand for fetching particular resources, we will l
prettier ./FILE_PATH.ts --write
```

[dprint](https://dprint.dev/cli/) - the super fast one
[biome](https://biomejs.dev) - the super fast one

```sh
dprint fmt ./FILE_PATH.ts
biome check ./FILE_PATH.ts --apply-unsafe
```

You are not limited to any of these, but in our examples we will use Prettier. Please remember that these tools needs to be installed first and they need a config file in your project.
Expand Down
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swaggie",
"version": "0.8.4",
"version": "0.8.5",
"description": "Generate ES6 or TypeScript service integration code from an OpenAPI spec",
"author": {
"name": "Piotr Dabrowski",
Expand Down Expand Up @@ -29,7 +29,10 @@
"types": "tsc src/types.ts --outDir dist/ --declaration --emitDeclarationOnly && cp test/index.d.ts ./dist/",
"test": "mocha"
},
"files": ["dist", "templates"],
"files": [
"dist",
"templates"
],
"keywords": [
"swagger",
"swagger 2.0",
Expand All @@ -49,15 +52,15 @@
"node-fetch": "^2.6.7"
},
"devDependencies": {
"@types/chai": "4.3.14",
"@types/chai": "4.3.16",
"@types/js-yaml": "4.0.9",
"@types/mocha": "10.0.6",
"@types/node-fetch": "2.6.11",
"@types/sinon": "17.0.3",
"chai": "4.4.1",
"mocha": "10.4.0",
"sinon": "17.0.1",
"sinon": "18.0.0",
"sucrase": "3.35.0",
"typescript": "5.4.3"
"typescript": "5.4.5"
}
}
25 changes: 21 additions & 4 deletions schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,14 @@
"template": {
"default": "axios",
"description": "Template that will be used for generating the API client. You can reference bundled templates by name or provide path to the custom template as well",
"examples": ["axios", "swr-axios", "fetch", "ng1", "ng2"],
"examples": [
"axios",
"xior",
"swr-axios",
"fetch",
"ng1",
"ng2"
],
"type": "string"
},
"baseUrl": {
Expand All @@ -44,13 +51,23 @@
"dateFormat": {
"default": "Date",
"description": "It determines how Date fields will be handled and what type they will have in models",
"enum": ["Date", "string"],
"enum": [
"Date",
"string"
],
"type": "string"
}
},
"required": ["out", "src"],
"required": [
"out",
"src"
],
"type": "object"
}
},
"allOf": [{ "$ref": "#/definitions/Globals" }]
"allOf": [
{
"$ref": "#/definitions/Globals"
}
]
}
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export interface ApiSpec {
contentTypes: string[];
}

export type Template = 'axios' | 'fetch' | 'ng1' | 'ng2' | 'swr-axios';
export type Template = 'axios' | 'fetch' | 'ng1' | 'ng2' | 'swr-axios' | 'xior';
export type HttpMethod = 'get' | 'put' | 'post' | 'delete' | 'options' | 'head' | 'patch';
export type DateSupport = 'string' | 'Date'; // 'luxon', 'momentjs', etc

Expand Down
10 changes: 10 additions & 0 deletions templates/xior/barrel.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

function serializeQueryParam(obj: any) {
if (obj === null || obj === undefined) return '';
if (obj instanceof Date) return obj.toJSON();
if (typeof obj !== 'object' || Array.isArray(obj)) return obj;
return Object.keys(obj)
.reduce((a: any, b) => a.push(b + '=' + obj[b]) && a, [])
.join('&');
}

17 changes: 17 additions & 0 deletions templates/xior/baseClient.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
// Generated using Swaggie (https://github.com/yhnavein/swaggie)
// Please avoid doing any manual changes in this file
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming
// deno-lint-ignore-file

import xior, { type XiorResponse, type XiorRequestConfig } from "xior";

export const http = xior.create({
baseURL: '<%= it.baseUrl || '' %>',
});

7 changes: 7 additions & 0 deletions templates/xior/client.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const <%= it.camelCaseName %>Client = {
<% it.operations.forEach((operation) => { %>
<%~ include('operation.ejs', operation); %>
<% }); %>
};

59 changes: 59 additions & 0 deletions templates/xior/operation.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
<% it.parameters.forEach((parameter) => { %>
* @param <%= parameter.name %> <%= parameter.optional ? '(optional)' : '' %> <%= parameter.name !== parameter.originalName ? `(API name: ${parameter.originalName})` : '' %>
<% }); -%>
*/
<%= it.name %>(<% it.parameters.forEach((parameter) => { %>
<%= parameter.name %>: <%~ parameter.type %> <%= parameter.optional ? '| null | undefined' : '' %>,
<% }); %>
$config?: XiorRequestConfig
): Promise<XiorResponse<<%~ it.returnType %>>> {
let url = '<%= it.url %>';
<% if(it.pathParams && it.pathParams.length > 0) {
it.pathParams.forEach((parameter) => { %>
url = url.replace('{<%= parameter.name %>}', encodeURIComponent("" + <%= parameter.name %>));
<% });
} %>
<% if(it.formData && it.formData.length > 0) { %>
const formDataBody = new FormData();
<% it.formData.forEach((parameter) => { %>
if (!!<%= parameter.name %>) {
<% if(parameter.original && parameter.original.type === 'array') { %>
<%= parameter.name %>.forEach((f: any) => formDataBody.append("<%= parameter.originalName %>", f));
<% } else { %>
formDataBody.append("<%= parameter.originalName %>", <%= parameter.name %><%= parameter.type !== 'string' && parameter.type !== 'File' && parameter.type !== 'Blob' ? '.toString()' : '' %>);
<% } %>
}
<% });
} %>

return http.request<<%~ it.returnType %>>({
url: url,
method: '<%= it.method %>',
<% if(it.formData && it.formData.length > 0) { %>
data: formDataBody,
<% } else if(it.body) { %>
data: <%= it.body.name %>,
<% } %>
<% if(it.query && it.query.length > 0) { %>
params: {
<% it.query.forEach((parameter) => { %>
'<%= parameter.originalName %>': serializeQueryParam(<%= parameter.name %>),
<% }); %>
},
<% } %>
<% if(it.headers && it.headers.length > 0) { %>
headers: {
<% it.headers.forEach((parameter) => { %>
<% if (parameter.value) { %>
'<%= parameter.originalName %>': '<%= parameter.value %>',
<% } else { %>
'<%= parameter.originalName %>': <%= parameter.name %>,
<% } %>
<% }); %>
},
<% } %>
...$config,
});
},
2 changes: 1 addition & 1 deletion test/snapshots.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import fs from 'fs';
import { runCodeGenerator } from '../src/index';
import { FullAppOptions, Template } from '../src/types';

const templates: Template[] = ['axios', 'swr-axios', 'fetch', 'ng1', 'ng2'];
const templates: Template[] = ['axios', 'xior', 'swr-axios', 'fetch', 'ng1', 'ng2'];

describe('petstore snapshots', () => {
templates.forEach((template) => {
Expand Down
Loading

0 comments on commit cba4f9a

Please sign in to comment.