├── LICENSE ├── README.md ├── client.js ├── controller └── syncController.js ├── index.js ├── interfaceSyncUtils.js ├── package.json ├── server.js ├── swaggerAutoSync └── swaggerAutoSync.js └── syncModel.js /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # yapi-plugin-swagger-auto-sync 2 | 这是一个能够让YAPI根据你配置的规则实时同步接口数据的插件,YAPI已经默认集成 3 | -------------------------------------------------------------------------------- /client.js: -------------------------------------------------------------------------------- 1 | import swaggerAutoSync from './swaggerAutoSync/swaggerAutoSync.js' 2 | 3 | function hander(routers) { 4 | routers.test = { 5 | name: 'Swagger自动同步', 6 | component: swaggerAutoSync 7 | }; 8 | } 9 | 10 | module.exports = function() { 11 | this.bindHook('sub_setting_nav', hander); 12 | }; 13 | -------------------------------------------------------------------------------- /controller/syncController.js: -------------------------------------------------------------------------------- 1 | const baseController = require('controllers/base.js'); 2 | const yapi = require('yapi.js'); 3 | const syncModel = require('../syncModel.js'); 4 | const projectModel = require('models/project.js'); 5 | const interfaceSyncUtils = require('../interfaceSyncUtils.js') 6 | 7 | class syncController extends baseController { 8 | constructor(ctx) { 9 | super(ctx); 10 | this.syncModel = yapi.getInst(syncModel); 11 | this.projectModel = yapi.getInst(projectModel); 12 | this.interfaceSyncUtils = yapi.getInst(interfaceSyncUtils); 13 | } 14 | 15 | /** 16 | * 保存定时任务 17 | * @param {*} ctx 18 | */ 19 | async upSync(ctx) { 20 | let requestBody = ctx.request.body; 21 | let projectId = requestBody.project_id; 22 | if (!projectId) { 23 | return (ctx.body = yapi.commons.resReturn(null, 408, '缺少项目Id')); 24 | } 25 | let result; 26 | if (requestBody.id) { 27 | result = await this.syncModel.up(requestBody); 28 | } else { 29 | result = await this.syncModel.save(requestBody); 30 | } 31 | 32 | //操作定时任务 33 | if (requestBody.is_sync_open) { 34 | this.interfaceSyncUtils.addSyncJob(projectId, requestBody.sync_cron, requestBody.sync_json_url, requestBody.sync_mode, requestBody.uid); 35 | } else { 36 | this.interfaceSyncUtils.deleteSyncJob(projectId); 37 | } 38 | return (ctx.body = yapi.commons.resReturn(result)); 39 | } 40 | 41 | /** 42 | * 查询定时任务 43 | * @param {*} ctx 44 | */ 45 | async getSync(ctx) { 46 | let projectId = ctx.query.project_id; 47 | if (!projectId) { 48 | return (ctx.body = yapi.commons.resReturn(null, 408, '缺少项目Id')); 49 | } 50 | let result = await this.syncModel.getByProjectId(projectId); 51 | return (ctx.body = yapi.commons.resReturn(result)); 52 | } 53 | 54 | } 55 | 56 | 57 | module.exports = syncController; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | server: true, 3 | client: true 4 | } -------------------------------------------------------------------------------- /interfaceSyncUtils.js: -------------------------------------------------------------------------------- 1 | const schedule = require('node-schedule'); 2 | const openController = require('controllers/open.js'); 3 | const projectModel = require('models/project.js'); 4 | const syncModel = require('./syncModel.js'); 5 | const tokenModel = require('models/token.js'); 6 | const yapi = require('yapi.js') 7 | const sha = require('sha.js'); 8 | const md5 = require('md5'); 9 | const { getToken } = require('utils/token'); 10 | const jobMap = new Map(); 11 | 12 | class syncUtils { 13 | 14 | constructor(ctx) { 15 | yapi.commons.log("-------------------------------------interfaceSyncUtils constructor-----------------------------------------------"); 16 | this.ctx = ctx; 17 | this.openController = yapi.getInst(openController); 18 | this.syncModel = yapi.getInst(syncModel); 19 | this.tokenModel = yapi.getInst(tokenModel) 20 | this.projectModel = yapi.getInst(projectModel); 21 | this.init() 22 | } 23 | 24 | //初始化定时任务 25 | async init() { 26 | let allSyncJob = await this.syncModel.listAll(); 27 | for (let i = 0, len = allSyncJob.length; i < len; i++) { 28 | let syncItem = allSyncJob[i]; 29 | if (syncItem.is_sync_open) { 30 | this.addSyncJob(syncItem.project_id, syncItem.sync_cron, syncItem.sync_json_url, syncItem.sync_mode, syncItem.uid); 31 | } 32 | } 33 | } 34 | 35 | /** 36 | * 新增同步任务. 37 | * @param {*} projectId 项目id 38 | * @param {*} cronExpression cron表达式,针对定时任务 39 | * @param {*} swaggerUrl 获取swagger的地址 40 | * @param {*} syncMode 同步模式 41 | * @param {*} uid 用户id 42 | */ 43 | async addSyncJob(projectId, cronExpression, swaggerUrl, syncMode, uid) { 44 | let projectToken = await this.getProjectToken(projectId, uid); 45 | //立即执行一次 46 | this.syncInterface(projectId, cronExpression, swaggerUrl, syncMode, uid, projectToken); 47 | let scheduleItem = schedule.scheduleJob(cronExpression, async () => { 48 | this.syncInterface(projectId, cronExpression, swaggerUrl, syncMode, uid, projectToken); 49 | }); 50 | 51 | //判断是否已经存在这个任务 52 | let jobItem = jobMap.get(projectId); 53 | if (jobItem) { 54 | jobItem.cancel(); 55 | } 56 | jobMap.set(projectId, scheduleItem); 57 | } 58 | 59 | //同步接口 60 | async syncInterface(projectId, cronExpression, swaggerUrl, syncMode, uid, projectToken) { 61 | yapi.commons.log('定时器触发, syncJsonUrl:' + swaggerUrl + ",合并模式:" + syncMode); 62 | let oldPorjectData; 63 | try { 64 | oldPorjectData = await this.projectModel.get(projectId); 65 | } catch(e) { 66 | yapi.commons.log('获取项目:' + projectId + '失败'); 67 | this.deleteSyncJob(projectId); 68 | //删除数据库定时任务 69 | await this.syncModel.delByProjectId(projectId); 70 | return; 71 | } 72 | //如果项目已经删除了 73 | if (!oldPorjectData) { 74 | yapi.commons.log('项目:' + projectId + '不存在'); 75 | this.deleteSyncJob(projectId); 76 | //删除数据库定时任务 77 | await this.syncModel.delByProjectId(projectId); 78 | return; 79 | } 80 | let newSwaggerJsonData; 81 | try { 82 | newSwaggerJsonData = await this.getSwaggerContent(swaggerUrl) 83 | if (!newSwaggerJsonData || typeof newSwaggerJsonData !== 'object') { 84 | yapi.commons.log('数据格式出错,请检查') 85 | this.saveSyncLog(0, syncMode, "数据格式出错,请检查", uid, projectId); 86 | } 87 | newSwaggerJsonData = JSON.stringify(newSwaggerJsonData) 88 | } catch (e) { 89 | this.saveSyncLog(0, syncMode, "获取数据失败,请检查", uid, projectId); 90 | yapi.commons.log('获取数据失败' + e.message) 91 | } 92 | 93 | let oldSyncJob = await this.syncModel.getByProjectId(projectId); 94 | 95 | //更新之前判断本次swagger json数据是否跟上次的相同,相同则不更新 96 | if (oldSyncJob.old_swagger_content && oldSyncJob.old_swagger_content == md5(newSwaggerJsonData)) { 97 | //记录日志 98 | this.saveSyncLog(0, syncMode, "接口无更新", uid, projectId); 99 | oldSyncJob.last_sync_time = yapi.commons.time(); 100 | await this.syncModel.upById(projectId, oldSyncJob); 101 | return; 102 | } 103 | 104 | let _params = { 105 | type: 'swagger', 106 | json: newSwaggerJsonData, 107 | project_id: projectId, 108 | merge: syncMode, 109 | token: projectToken 110 | } 111 | let requestObj = { 112 | params: _params 113 | }; 114 | await this.openController.importData(requestObj); 115 | 116 | //修改project的属性 117 | oldSyncJob.last_sync_time = yapi.commons.time(); 118 | oldSyncJob.old_swagger_content = md5(newSwaggerJsonData); 119 | await this.syncModel.upById(oldSyncJob._id, oldSyncJob) 120 | 121 | //记录日志 122 | this.saveSyncLog(requestObj.body.errcode, syncMode, requestObj.body.errmsg, uid, projectId); 123 | } 124 | 125 | getSyncJob(projectId) { 126 | return jobMap.get(projectId); 127 | } 128 | 129 | deleteSyncJob(projectId) { 130 | let jobItem = jobMap.get(projectId); 131 | if (jobItem) { 132 | jobItem.cancel(); 133 | } 134 | } 135 | 136 | /** 137 | * 记录同步日志 138 | * @param {*} errcode 139 | * @param {*} syncMode 140 | * @param {*} moremsg 141 | * @param {*} uid 142 | * @param {*} projectId 143 | */ 144 | saveSyncLog(errcode, syncMode, moremsg, uid, projectId) { 145 | yapi.commons.saveLog({ 146 | content: '自动同步接口状态:' + (errcode == 0 ? '成功,' : '失败,') + "合并模式:" + this.getSyncModeName(syncMode) + ",更多信息:" + moremsg, 147 | type: 'project', 148 | uid: uid, 149 | username: "自动同步用户", 150 | typeid: projectId 151 | }); 152 | } 153 | 154 | /** 155 | * 获取项目token,因为导入接口需要鉴权. 156 | * @param {*} project_id 项目id 157 | * @param {*} uid 用户id 158 | */ 159 | async getProjectToken(project_id, uid) { 160 | try { 161 | let data = await this.tokenModel.get(project_id); 162 | let token; 163 | if (!data) { 164 | let passsalt = yapi.commons.randStr(); 165 | token = sha('sha1') 166 | .update(passsalt) 167 | .digest('hex') 168 | .substr(0, 20); 169 | 170 | await this.tokenModel.save({ project_id, token }); 171 | } else { 172 | token = data.token; 173 | } 174 | 175 | token = getToken(token, uid); 176 | 177 | return token; 178 | } catch (err) { 179 | return ""; 180 | } 181 | } 182 | 183 | getUid(uid) { 184 | return parseInt(uid, 10); 185 | } 186 | 187 | /** 188 | * 转换合并模式的值为中文. 189 | * @param {*} syncMode 合并模式 190 | */ 191 | getSyncModeName(syncMode) { 192 | if (syncMode == 'good') { 193 | return '智能合并'; 194 | } else if (syncMode == 'normal') { 195 | return '普通模式'; 196 | } else if (syncMode == 'merge') { 197 | return '完全覆盖'; 198 | } 199 | return ''; 200 | } 201 | 202 | async getSwaggerContent(swaggerUrl) { 203 | const axios = require('axios') 204 | try { 205 | let response = await axios.get(swaggerUrl); 206 | if (response.status > 400) { 207 | throw new Error(`http status "${response.status}"` + '获取数据失败,请确认 swaggerUrl 是否正确') 208 | } 209 | return response.data; 210 | } catch (e) { 211 | let response = e.response; 212 | throw new Error(`http status "${response.status}"` + '获取数据失败,请确认 swaggerUrl 是否正确') 213 | } 214 | } 215 | 216 | } 217 | 218 | module.exports = syncUtils; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "yapi-plugin-swagger-auto-sync", 3 | "version": "0.0.1", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "Apache-2.0", 11 | "dependencies": { 12 | "node-schedule": "^1.3.2" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | const controller = require('./controller/syncController.js'); 2 | const yapi =require('yapi.js'); 3 | const interfaceSyncUtils = require('./interfaceSyncUtils.js'); 4 | 5 | module.exports = function () { 6 | yapi.getInst(interfaceSyncUtils); 7 | 8 | this.bindHook('add_router', function (addRouter) { 9 | addRouter({ 10 | controller: controller, 11 | method: 'get', 12 | path: 'autoSync/get', 13 | action: 'getSync' 14 | }); 15 | addRouter({ 16 | controller: controller, 17 | method: 'post', 18 | path: 'autoSync/save', 19 | action: 'upSync' 20 | }); 21 | addRouter({ 22 | /** 23 | * 保存期望 24 | */ 25 | controller: controller, 26 | method: 'post', 27 | path: 'autoSync/upd', 28 | action: 'saveCase' 29 | }); 30 | 31 | }); 32 | 33 | }; -------------------------------------------------------------------------------- /swaggerAutoSync/swaggerAutoSync.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import PropTypes from 'prop-types'; 4 | import { formatTime } from 'client/common.js'; 5 | import { Form, Switch, Button, Icon, Tooltip, message, Input, Select } from 'antd'; 6 | import {handleSwaggerUrlData} from 'client/reducer/modules/project'; 7 | const FormItem = Form.Item; 8 | const Option = Select.Option; 9 | import axios from 'axios'; 10 | 11 | // layout 12 | const formItemLayout = { 13 | labelCol: { 14 | lg: { span: 5 }, 15 | xs: { span: 24 }, 16 | sm: { span: 10 } 17 | }, 18 | wrapperCol: { 19 | lg: { span: 16 }, 20 | xs: { span: 24 }, 21 | sm: { span: 12 } 22 | }, 23 | className: 'form-item' 24 | }; 25 | const tailFormItemLayout = { 26 | wrapperCol: { 27 | sm: { 28 | span: 16, 29 | offset: 11 30 | } 31 | } 32 | }; 33 | 34 | @connect( 35 | state => { 36 | return { 37 | projectMsg: state.project.currProject 38 | }; 39 | }, 40 | { 41 | handleSwaggerUrlData 42 | } 43 | ) 44 | @Form.create() 45 | export default class ProjectInterfaceSync extends Component { 46 | static propTypes = { 47 | form: PropTypes.object, 48 | match: PropTypes.object, 49 | projectId: PropTypes.number, 50 | projectMsg: PropTypes.object, 51 | handleSwaggerUrlData: PropTypes.func 52 | }; 53 | 54 | constructor(props) { 55 | super(props); 56 | this.state = { 57 | sync_data: { is_sync_open: false } 58 | }; 59 | } 60 | 61 | handleSubmit = async () => { 62 | const { form, projectId } = this.props; 63 | let params = { 64 | project_id: projectId, 65 | is_sync_open: this.state.sync_data.is_sync_open, 66 | uid: this.props.projectMsg.uid 67 | }; 68 | if (this.state.sync_data._id) { 69 | params.id = this.state.sync_data._id; 70 | } 71 | form.validateFields(async (err, values) => { 72 | if (!err) { 73 | let assignValue = Object.assign(params, values); 74 | await axios.post('/api/plugin/autoSync/save', assignValue).then(res => { 75 | if (res.data.errcode === 0) { 76 | message.success('保存成功'); 77 | } else { 78 | message.error(res.data.errmsg); 79 | } 80 | }); 81 | } 82 | }); 83 | 84 | }; 85 | 86 | validSwaggerUrl = async (rule, value, callback) => { 87 | try{ 88 | await this.props.handleSwaggerUrlData(value); 89 | } catch(e) { 90 | callback('swagger地址不正确'); 91 | } 92 | callback() 93 | } 94 | 95 | componentWillMount() { 96 | //查询同步任务 97 | this.setState({ 98 | sync_data: {} 99 | }); 100 | this.getSyncData(); 101 | } 102 | 103 | async getSyncData() { 104 | let projectId = this.props.projectMsg._id; 105 | let result = await axios.get('/api/plugin/autoSync/get?project_id=' + projectId); 106 | if (result.data.errcode === 0) { 107 | if (!result.data.data) { 108 | this.state.sync_data.is_sync_open = false; 109 | this.setState(this.state); 110 | } else { 111 | this.setState({ 112 | sync_data: result.data.data 113 | }); 114 | } 115 | } 116 | } 117 | 118 | // 是否开启 119 | onChange = v => { 120 | this.state.sync_data.is_sync_open = v; 121 | this.setState(this.state); 122 | }; 123 | 124 | render() { 125 | const { getFieldDecorator } = this.props.form; 126 | return ( 127 |
128 |
129 | 133 | 139 | {this.state.sync_data.last_sync_time != null ? (
上次更新时间:{formatTime(this.state.sync_data.last_sync_time)}
) : null} 140 |
141 | 142 |
143 | 145 | 数据同步  146 | 149 |

普通模式

150 |

不导入已存在的接口

151 |
152 |

智能合并

153 |

154 | 已存在的接口,将合并返回数据的 response,适用于导入了 swagger 155 | 数据,保留对数据结构的改动 156 |

157 |
158 |

完全覆盖

159 |

不保留旧数据,完全使用新数据,适用于接口定义完全交给后端定义

160 |
161 | } 162 | > 163 | 164 | {' '} 165 | 166 | }> 167 | {getFieldDecorator('sync_mode', { 168 | initialValue: this.state.sync_data.sync_mode, 169 | rules: [ 170 | { 171 | required: true, 172 | message: '请选择同步方式!' 173 | } 174 | ] 175 | })( 176 | 177 | 182 | )} 183 | 184 | 185 | 186 | {getFieldDecorator('sync_json_url', { 187 | rules: [ 188 | { 189 | required: true, 190 | message: '输入swagger地址' 191 | }, 192 | { 193 | validator: this.validSwaggerUrl 194 | } 195 | ], 196 | validateTrigger: 'onBlur', 197 | initialValue: this.state.sync_data.sync_json_url 198 | })()} 199 | 200 | 201 | 类cron风格表达式(默认每分钟更新一次) 参考}> 202 | {getFieldDecorator('sync_cron', { 203 | rules: [ 204 | { 205 | required: true, 206 | message: '输入node-schedule的类cron表达式!' 207 | } 208 | ], 209 | initialValue: this.state.sync_data.sync_cron ? this.state.sync_data.sync_cron : '30 * * * * *' 210 | })()} 211 | 212 |
213 | 214 | 217 | 218 | 219 | 220 | ); 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /syncModel.js: -------------------------------------------------------------------------------- 1 | const yapi = require('yapi.js'); 2 | const baseModel = require('models/base.js'); 3 | const mongoose = require('mongoose'); 4 | 5 | class syncModel extends baseModel { 6 | getName() { 7 | return 'interface_auto_sync'; 8 | } 9 | 10 | getSchema() { 11 | return { 12 | uid: { type: Number}, 13 | project_id: { type: Number, required: true }, 14 | //是否开启自动同步 15 | is_sync_open: { type: Boolean, default: false }, 16 | //自动同步定时任务的cron表达式 17 | sync_cron: String, 18 | //自动同步获取json的url 19 | sync_json_url: String, 20 | //接口合并模式 good,nomarl等等 意思也就是智能合并,完全覆盖等 21 | sync_mode: String, 22 | //上次成功同步接口时间, 23 | last_sync_time: Number, 24 | //上次同步的swagger 文档内容 25 | old_swagger_content: String, 26 | add_time: Number, 27 | up_time: Number, 28 | }; 29 | } 30 | 31 | getByProjectId(id) { 32 | return this.model.findOne({ 33 | project_id: id 34 | }) 35 | } 36 | 37 | delByProjectId(project_id){ 38 | return this.model.remove({ 39 | project_id: project_id 40 | }) 41 | } 42 | 43 | save(data) { 44 | data.up_time = yapi.commons.time(); 45 | let m = new this.model(data); 46 | return m.save(); 47 | } 48 | 49 | listAll() { 50 | return this.model 51 | .find({}) 52 | .select( 53 | '_id uid project_id add_time up_time is_sync_open sync_cron sync_json_url sync_mode old_swagger_content last_sync_time' 54 | ) 55 | .sort({ _id: -1 }) 56 | .exec(); 57 | } 58 | 59 | up(data) { 60 | let id = data.id; 61 | delete data.id; 62 | data.up_time = yapi.commons.time(); 63 | return this.model.update({ 64 | _id: id 65 | }, data) 66 | } 67 | 68 | upById(id, data) { 69 | delete data.id; 70 | data.up_time = yapi.commons.time(); 71 | return this.model.update({ 72 | _id: id 73 | }, data) 74 | } 75 | 76 | del(id){ 77 | return this.model.remove({ 78 | _id: id 79 | }) 80 | } 81 | 82 | delByProjectId(projectId){ 83 | return this.model.remove({ 84 | project_id: projectId 85 | }) 86 | } 87 | 88 | } 89 | 90 | module.exports = syncModel; --------------------------------------------------------------------------------