Swagger brief introduction

Swagger/Open API has gradually become the standard in the field of Restful API, and more and more systems use Swagger to standardize the development interface documents. Since Swagger itself does not depend on a specific language and development platform, it is particularly suitable to be used as the interface standard for the separation of the front and back ends. Swagger UI provides two official document UI forms, Swagger UI and Swagger Editor.

  • Swagger UI is often used as a part of project engineering, and many programs adopt their own characteristics to add annotations, annotations, decorators to the program code to complete automatic generation and presentation of Swagger interface documents.

  • Swagger Editor provides an online Editor that allows you to edit the interface in a document-like manner, and provides two types of generation: server-side code and client-side code. Code generation covers most of the major languages and frameworks very conveniently.

Directly usable code

Many of you may wonder, does the generated code actually work?

My answer is not only yes, it works. Ng – alain, for example

Code location github.com/vellengs/ty… Customize the Provider basePath Settings.

export function apiConfig(): Configuration {
    return new Configuration({
        basePath: `${location.protocol}//${location.host}`}); }Copy the code

Register the next module

ApiModule.forRoot(apiConfig),
Copy the code

Then release the directory to github.com/vellengs/ty… Generted directory: Generted directory: generted directory: Generted directory: Generted directory

Once placed in an Angular project, you can happily use a service, as shown in the following example: github.com/vellengs/ty…

profileSave(event?) {
    const entry: EditProfileDto = Object.assign({}, event);
    this.coreService.userUpdate(entry).subscribe((res) => {
        if (res) {
            this.settings.setUser(res);
            this.msg.success('Personal Data modified successfully'); }}); } saveSysSettings(event) { const entry = Object.assign({}, event); this.coreService.settingUpdateSettingsByName('main', entry).subscribe((res) => {
        if (res) {
            this.settingsData = res;
            this.msg.success('System Settings updated successfully'); }}); }load() {
    this.coreService.settingGetSettingsByName('main').subscribe((res) => {
        if(res) { this.settingsData = res; }}); }Copy the code

Methods become perceptive.

Automatic generation, download, decompress

The previous step is ready to use, but there is a little trouble; Every time you open editor.swagger. IO and paste it in, then go to Generate, and then unzip it.

Let’s write a script that will do this automatically. Full script address

async function loadSwagger*/ const jsonPath = path.resolve(process.cwd(),'dist'.'swagger.json');
    const json = require(jsonPath);

    const client = axios.create({
        httpsAgent: new https.Agent({
            rejectUnauthorized: false})}); /** * const result = await client.post(gateway, {spec: json});if (result.data && result.data.link) {
        const response = await client({
            method: 'GET',
            url: result.data.link,
            responseType: 'stream'
        })
        const local = path.resolve(process.cwd(), 'swagger.zip');
        const generatedFolder = path.resolve(process.cwd(), '. /.. /client/src/generated');
        const templateFolder = path.resolve(process.cwd(), 'decompress'.'typescript-angular-client');
        const decompress = path.resolve(process.cwd(), 'decompress'); Response.data. pipe(fs.createWritestream (fs.createWritestream))local)).on('finish', (done: any) => {
            fs.createReadStream(local).pipe(unzip.Extract({ path: 'decompress' })).on('close',
                async (done: any) => {
             
                    fs.unlinkSync(local); await removeFolder(generatedFolder); fs.renameSync(templateFolder, generatedFolder); await removeFolder(decompress); }); }); }} /** * If already generated, delete folder * @param Folder folder */ asyncfunction removeFolder(folder: string) {
    if (fs.existsSync(folder)) {
        await new Promise((resolve) => {
            rimraf(folder, () => {
                resolve(true);
            });
        })
    }
}

loadSwagger();
Copy the code

It’s only a few lines of code, so it’s pretty simple, yeah, it’s pretty simple, but it does our job.

Once you have the script you just

ts-node  xxxxx/apigen.ts 
Copy the code

Can get the job done.

In conclusion, the standard interface plays a good normative role in the development of the front and back end separation, and the smooth development experience is also an important part. If you have any questions, or have a better way, welcome to communicate with the author to learn github.com/vellengs