- src/api/jimmerApi.ts
import { Api } from '../_generated';
import { defHttp } from '/@/utils/http/axios';
const BASE_URL = import.meta.env.VITE_API_JIMMER_BASE_URL;
export const api = new Api(async ({ uri, method, body }) => {
return defHttp.request({
url: `${BASE_URL}${uri}`,
method,
params: body,
});
});
export const api1 = new Api(async ({ uri, method, body }) => {
const tenant = (window as any).__tenant as string | undefined;
const response = await fetch(`${BASE_URL}${uri}`, {
method,
body: body !== undefined ? JSON.stringify(body) : undefined,
headers: {
'content-type': 'application/json;charset=UTF-8',
...(tenant !== undefined && tenant !== '' ? { tenant } : {}),
},
});
if (response.status !== 200) {
throw await response.json();
}
const text = await response.text();
if (text.length === 0) {
return undefined;
}
return JSON.parse(text);
});
- views/demo/system/jimmer/index.vue
<template>
<div>
<input v-model="options.id" placeholder="请输入文本" />
<button @click="query">成功按钮</button>
{{ data.id }}
</div>
</template>
<script lang="ts" setup name="list">
import { api } from '/@/api/JimmerApi';
import { RequestOf, ResponseOf } from '/@/_generated';
import { ref } from 'vue';
const options = ref(<RequestOf<typeof api.bookService.findComplexBook>>{});
let data = ref(<Exclude<ResponseOf<typeof api.bookService.findComplexBook>, undefined>>{});
const query = () => {
api.bookService
.findComplexBook(options.value)
.then((res) => {
if (res === undefined || res === null) {
alert('未查询到数据');
return;
}
data.value = res as Exclude<ResponseOf<typeof api.bookService.findComplexBook>, undefined>;
})
.catch((err) => {
alert('查询接口出错了:' + JSON.stringify(err));
});
};
</script>
<style lang="scss" scoped></style>
- package.json
"api": "node scripts/generate-api.js"
"js-yaml": "^4.1.0",
"adm-zip": "^0.5.10",
- scripts/generate-api.js
// import http from 'http';
// import fs from 'fs';
// import unzipper from 'unzipper';
// import {createRequire} from 'module'
//
// const require = createRequire(import.meta.url)
const http = require('node:http');
const fs = require('node:fs');
const fse = require('fs-extra');
const AdmZip = require('adm-zip');
const yaml = require('js-yaml');
const sourceUrl = 'http://localhost:8080/ts.zip';
const apiUrl = 'http://localhost:8080/openapi.yml';
const generatePath = 'src/api/__generated';
const tmpFilePath = generatePath + '.zip';
console.log('Downloading ' + sourceUrl + '...');
const tmpFile = fs.createWriteStream(tmpFilePath);
const request = http.get(sourceUrl, (response) => {
response.pipe(tmpFile);
tmpFile.on('finish', () => {
tmpFile.close();
console.log('File save success: ', tmpFilePath);
// Remove generatePath if it exists
if (fs.existsSync(generatePath)) {
console.log('Removing existing generatePath...');
fse.removeSync(generatePath);
console.log('Existing generatePath removed.');
}
// Unzip the file using adm-zip
console.log('Unzipping the file...');
const zip = new AdmZip(tmpFilePath);
zip.extractAllTo(generatePath, true);
console.log('File unzipped successfully.');
// Remove the temporary file
console.log('Removing temporary file...');
fs.unlink(tmpFilePath, (err) => {
if (err) {
console.error('Error while removing temporary file:', err);
} else {
console.log('Temporary file removed.');
}
});
if (apiUrl) {
// const apiDoc = fs.readFileSync(new URL(apiUrl), 'utf8')
http.get(
apiUrl,
(resp) => {
const apiTemp = fs.createWriteStream(generatePath + '/api.yml');
resp.pipe(apiTemp);
apiTemp.on('finish', () => {
const temp = {};
const doc = yaml.load(fs.readFileSync(generatePath + '/api.yml', 'utf8'));
doc &&
Object.keys(doc.paths).forEach((key) => {
const path = doc.paths[key];
const { operationId, parameters, requestBody, responses, summary, tags } = path[Object.keys(path)[0]];
const typeKey = (tags[0] += "['" + operationId + "']");
temp[typeKey] = { method: Object.keys(path)[0], parameters, requestBody, responses, summary };
});
fs.writeFileSync(generatePath + '/types.json', JSON.stringify(temp));
const tempSchema = {};
doc &&
doc.components &&
Object.keys(doc.components.schemas).forEach((key) => {
const schema = doc.components.schemas[key];
const { properties } = schema;
const typeKey = '#/components/schemas/' + key;
tempSchema[typeKey] = properties;
});
fs.writeFileSync(generatePath + '/schemas.json', JSON.stringify(tempSchema));
});
},
(err) => {
console.log(err);
}
);
}
});
});