Commit 4d38347f authored by 前端-许佳敏's avatar 前端-许佳敏

chore: 调整配置文件

parent 6767fa66
/**
* 手动上传文件
* @auth xjm
*/
const git = require('gulp-git')
const Logs = require('./utils/log')
const cmd = require('node-cmd')
const scpRun = require('@linkseeks/god-upload-scp')
const connectSSH = (done) => {
const sshInfo = JSON.parse(process.env.ssh)
scpRun(sshInfo, process.env.PRO_ENV, done)
}
const initUpload = (done) => {
Logs.stop('开始上传到远程服务器!', 'success')
connectSSH(done)
}
module.exports = {
initUpload
}
/**
* 用于build后在10.0.0.25环境下,作为本地调试
*
*/
//express模块
console.log(process.argv)
var express =require("express");
var app =express();
const path = require('path')
const { createProxyMiddleware } = require('http-proxy-middleware')
const port = 4396
const apiProxyTarget = 'http://10.0.0.25:8100'
// 用于解决刷新后404问题
var history = require('connect-history-api-fallback');
app.use('/api',createProxyMiddleware(
{
target: apiProxyTarget,
changeOrigin: true,
pathRewrite: { '^/api' : '' }
}
))
app.use(history());
app.use(express.static('dist'))
app.get('/',(req,res)=>{
res.sendFile(path.resolve(__dirname, "../dist/", "index.html")) //设置/ 下访问文件位置
});
var server =app.listen(port,()=>{
var port =server.address().port
console.log("【】访问地址http://localhost:%s",port)
})
\ No newline at end of file
const path = require('path')
const Logs = require('./utils/log')
const fse = require('fs-extra')
const Type = require('./utils/type')
const runFile = './services'
const fetchConfig = require(runFile).fetchConfig
const gulp = require('gulp')
const json2ts = require('json2ts')
const uploadBuildStram = require('./build')
const pullRemoteRouter = require('./pullRemoteRouterList')
const rootPath = '../';
const outputPath = path.resolve(__dirname, rootPath, 'config/base.config.json')
const outputDts = path.resolve(__dirname, rootPath, 'src/global/config/global.d.ts')
// Logs.start('gulp start')
gulp.task('start', gulp.series(done => {
startRemotePull(done)
}))
gulp.task('upload', gulp.series(done => {
Logs.start('use upload')
uploadBuildStram.initUpload(done)
}))
/**
* 生成对应json文件
*/
function genarateBaseJson(obj, done) {
if (Type.isObject(obj)) {
fse.ensureFile(outputPath).then(() => {
fse.writeJson(outputPath, obj).then(() => {
Logs.success('\nstart genarate config json')
Logs.success('write success')
Logs.stop('Configuration has arrived locally', 'success')
genarateDtsFile(JSON.stringify(obj), done)
}).catch(err => {
Logs.error(err)
done()
})
})
} else {
Logs.error('!!!!!! value is not a object !!!!!')
Logs.error(`here is your value, the type is ${typeof obj}`)
console.log(obj)
Logs.stop('Append error!!!', 'fail')
done()
}
}
function genarateDtsFile(json, done) {
const dtsResult = json2ts.convert(json)
fse.outputFile(outputDts, dtsResult).then(() => {
done()
})
}
/**
* 异步读取远程路由并写入
*/
async function startRemotePull(done) {
await pullRemoteRouter()
getAsyncConfig(done)
}
/**
* 异步获取远程配置
* @todo
*/
async function getAsyncConfig(done) {
const data = await fetchConfig()
genarateBaseJson(data, done)
}
const fs = require('fs');
const path = require('path');
/**
* 用于新项目启动时缺少必要文件, 做的初始化脚本
*/
const cwd = process.cwd();
async function init() {
try {
await ensureFile(cwdPath('config/base.config.json'), '{}');
await ensureFile(cwdPath('config/router.config.json'), '[]');
await ensureFile(cwdPath('yapi_hashmaps.json'), '{}');
} catch (error) {
console.log(error);
process.exit(1);
}
}
/**
* 判断文件是否存在,如果不存在则创建,并写入对应初始值
*/
async function ensureFile(pathFile, defaultData) {
return new Promise((resolve, reject) => {
fs.open(pathFile, 'wx', function(err) {
if (err) {
if (err.code === 'EEXIST') {
resolve()
}
reject(err)
return ;
}
fs.writeFile(pathFile, defaultData, function(err) {
if (err) {
console.error(`初始化${pathFile}失败`);
reject(err);
}
console.log(`初始化${pathFile}成功`);
resolve(defaultData);
});
return;
});
});
}
function cwdPath(filePath) {
return path.resolve(cwd, filePath);
}
init();
/**
* 用于在项目开始前获取所有的配置
* 在项目开始前运行`yarn scripts:build`
* @todo 缺少异常处理清空
* @author xjm
*/
const Axios = require('axios').default;
const deepClone = require('clone')
const fs = require('fs')
const path = require('path')
const BACK_GATEWAY = process.env.BACK_GATEWAY
const source = 1
const remoteUrl = BACK_GATEWAY || process.argv[2] || 'http://10.0.0.25:8100'
console.log(`\n当前访问的后端url是${remoteUrl}!!!!!!`)
const axios = Axios.create({
baseURL: remoteUrl,
responseType: 'json',
})
const serviceConfig = {
//初始化会员支付策略配置
router: {
componentList: {
url: '/system/menu/code/list',
method: 'get',
params: {
source
}
},
routerList: {
url: '/system/menu/tree',
method: 'get',
params: {
source
}
}
},
}
function code2component(components, codes) {
components.forEach(v => {
if (v.routes) {
code2component(v.routes, codes)
}
if (v.component) {
const codeResult = codes.find(c => c.code === v.component)
if (!codeResult) {
console.error(`出现不匹配的component->${v.component}\n`)
}
v.component = codeResult.url
}
})
}
// 批量组装接口
async function batchAxiosHttps() {
const asyncHttpQueue = deepClone(serviceConfig)
const httpErrorQueue = []
const serverErrorQueue = []
console.log('\n')
for (const item in serviceConfig) {
if (JSON.stringify(item) !== '{}') {
for (const subItem in serviceConfig[item]) {
try {
const data = await axios(serviceConfig[item][subItem])
// 当接口出错时 不写入json文件
if (data.data.code === 1000) {
asyncHttpQueue[item][subItem] = data.data.data
} else {
serverErrorQueue.push({ ...asyncHttpQueue[item][subItem], ...data.data })
// 默认置为null
asyncHttpQueue[item][subItem] = null
}
} catch (err) {
httpErrorQueue.push({ ...serviceConfig[item][subItem], ...err.response.data })
}
}
}
}
if (httpErrorQueue.length > 0) {
console.log('\n网络错误\n')
// 可在此做日志收集
console.log(httpErrorQueue)
}
if (serverErrorQueue.length > 0) {
console.log('接口服务错误\n')
// 可在此做日志收集
console.log(serverErrorQueue)
}
if (httpErrorQueue.length > 0 || serverErrorQueue.length > 0) {
// 退出构建
console.log('\n脚本构建失败!!!!!!')
// 终止当前进程
process.exit(1)
}
// fs.writeFile(path.resolve(__dirname, '../config/component.config.json'), `${JSON.stringify(asyncHttpQueue.router.componentList)}`, function(err) {
// if (err) throw err
// })
// code2component(asyncHttpQueue.router.routerList, asyncHttpQueue.router.componentList)
fs.writeFile(path.resolve(__dirname, '../config/router.config.json'), `${JSON.stringify(asyncHttpQueue.router.routerList)}`, function(err) {
if (err) throw err
})
}
module.exports = batchAxiosHttps
const gulp = require('gulp')
const envValue = require('../env')
const path = require('path')
const fs = require('fs')
const { setEnv, getEnv } = require('./utils/envTool')
const isProduction = process.env.NODE_ENV === 'production'
// @todo
const taskName = process.env.taskName || 'start'
/**
* 判断当前目录下是否存在远程配置文件, 如果不存在则新建
*/
function genarateConfig() {
const configPath = path.resolve('config/base.config.json')
const routePath = path.resolve('config/router.config.json')
fs.stat(configPath, function(err, stat) {
if (err) {
// 文件不存在则新建
fs.writeFile(configPath, '{}', function(err) {
if (err) throw err;
})
}
})
fs.stat(routePath, function(err, stat) {
if (err) {
// 文件不存在则新建
fs.writeFile(routePath, '[]', function(err) {
if (err) throw err;
})
}
})
}
// 构建时带上的环境变量
const PRO_ENV = process.env.PRO_ENV
if (!PRO_ENV) {
throw `请传入PRO_ENV`
}
setEnv(getEnv(envValue))
function runTask(toRun) {
const metadata = { task: toRun };
// Gulp >= 4.0.0 (doesn't support events)
const taskInstance = gulp.task(toRun);
if (taskInstance === undefined) {
gulp.emit('task_not_found', metadata);
return;
}
const start = process.hrtime();
gulp.emit('task_start', metadata);
try {
taskInstance.apply(gulp);
metadata.hrDuration = process.hrtime(start);
gulp.emit('task_stop', metadata);
gulp.emit('stop');
} catch (err) {
err.hrDuration = process.hrtime(start);
err.task = metadata.task;
gulp.emit('task_err', err);
}
}
require('./gulpfile')
genarateConfig()
runTask(taskName)
const Axios = require('axios').default;
const deepClone = require('clone')
const { prefixServiceConfig, serviceConfig} = require('./server')
const BACK_GATEWAY = process.env.BACK_GATEWAY
const demoFetch = require('../../demo').fetchConfig
const isDemo = true
const remoteUrl = BACK_GATEWAY || process.argv[2] || 'http://10.0.0.25:8100'
console.log(`\n当前访问的后端url是${remoteUrl}!!!!!!`)
const axios = Axios.create({
baseURL: remoteUrl,
responseType: 'json',
headers: {
"source": "1"
}
})
async function prefixHttp() {
try {
const { data } = await axios(prefixServiceConfig.global)
if (data.code === 1000) {
return data.data
} else {
return {}
}
} catch (error) {
console.log(error)
}
}
// 批量组装接口
async function batchAxiosHttps(requestConfig) {
const asyncHttpQueue = deepClone(serviceConfig)
const httpErrorQueue = []
const serverErrorQueue = []
console.log('\n')
for (const item in serviceConfig) {
if (JSON.stringify(item) !== '{}') {
for (const subItem in serviceConfig[item]) {
try {
axios.interceptors.request.use(config => {
config.headers = Object.assign({}, config.headers, requestConfig.headers)
return config
})
const data = await axios(serviceConfig[item][subItem])
// 当接口出错时 不写入json文件
if (data.data.code === 1000) {
asyncHttpQueue[item][subItem] = data.data.data
} else {
serverErrorQueue.push({ ...asyncHttpQueue[item][subItem], ...data.data })
// 默认置为null
asyncHttpQueue[item][subItem] = null
}
} catch (err) {
console.log(err)
httpErrorQueue.push({ ...serviceConfig[item][subItem], ...err.response.data })
}
}
}
}
if (httpErrorQueue.length > 0) {
console.log('\n网络错误\n')
// 可在此做日志收集
console.log(httpErrorQueue)
}
if (serverErrorQueue.length > 0) {
console.log('\n接口服务错误\n')
// 可在此做日志收集
console.log(serverErrorQueue)
}
if (httpErrorQueue.length > 0 || serverErrorQueue.length > 0) {
// 退出构建
console.log('\n脚本构建失败!!!!!!')
// 终止当前进程
process.exit(1)
}
return isDemo ? Object.assign(asyncHttpQueue, await demoFetch()) : asyncHttpQueue
}
module.exports = {
prefixHttp,
batchAxiosHttps,
}
/*
* @Author: LeeJiancong
* @Date: 2020-07-17 18:01:43
* @LastEditors: XieZhiXiong
* @Copyright: 1549414730@qq.com
* @LastEditTime: 2021-08-07 11:08:07
*/
/**
* 用于在项目开始前获取所有的配置
* 在项目开始前运行`yarn scripts:build`
* @todo 缺少异常处理清空
* @author xjm
*/
const Axios = require('axios').default;
const { prefixHttp, batchAxiosHttps } = require('./batchAxiosHttps')
const SITE_ID = Number(process.env.SITE_ID)
if (!SITE_ID) {
console.log('\n构建失败!!!!!!')
console.log('\n缺少站点ID')
process.exit(1)
}
async function pullConfigHttp() {
const data = await prefixHttp()
const { language = 'zh' } = data
console.log(`当前站点语言为${language}`)
const result = await batchAxiosHttps({
headers: {
'Accept-Language': language
}
})
return result
}
exports.fetchConfig = pullConfigHttp
const SITE_ID = Number(process.env.SITE_ID)
/**
* 前置接口 用于后续配置接口的信息获取
*/
const prefixServiceConfig = {
global: {
url: '/manage/paas/site/details',
params: {
id: SITE_ID
},
method: 'get'
}
}
const serviceConfig = {
// 用于注册页
userRegister: {
useType: {
url: '/member/menu/register/type',
method: 'get'
}
},
web: {
shopInfo: {
url: '/manage/shop/findShopsBySiteId',
params: {
siteId: SITE_ID,
},
method: 'get'
},
orderMode: {
url: '/system/rule/getOrderMode',
method: 'get'
},
orderType: {
url: '/system/rule/getOrderType',
method: 'get'
},
},
global: {
siteInfo: {
url: '/manage/paas/site/details',
params: {
id: SITE_ID
},
method: 'get'
},
imConfig: {
url: '/manage/online/service/find/config',
method: 'get'
},
},
}
module.exports = {
serviceConfig,
prefixServiceConfig
}
function getEnv(envConfig) {
if (!envConfig) {
throw `检查是否传入PRO_ENV`
}
return envConfig[process.env.PRO_ENV]
}
function setEnv(envs) {
Object.keys(envs).forEach(key => {
process.env[key] = envs[key]
})
}
module.exports = {
getEnv,
setEnv,
}
const chalk = require('chalk')
const ora = require('ora')
const spinner = ora('Loading remote configuration')
const log = console.log
const Logs = {
success(msg) {
log(chalk.green(msg))
},
error(msg) {
log(chalk.red(msg))
},
start(msg) {
spinner.start(msg)
return spinner
},
stop(msg, type) {
const instance = spinner.stop()
type === 'success' ? instance.succeed(msg) : instance.fail(msg)
}
}
module.exports = Logs
\ No newline at end of file
const Type = {
isObject(data) {
return Object.prototype.toString.call(data) === '[object Object]'
}
}
module.exports = Type
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment