80 行
2.1 KiB
TypeScript
80 行
2.1 KiB
TypeScript
import express, {Request, Response} from "express"
|
|
import {validationResult} from "express-validator"
|
|
import {IResultJson} from "./types"
|
|
import axios from "axios"
|
|
import axiosCookieJarSupport from "axios-cookiejar-support"
|
|
import tough from 'tough-cookie'
|
|
import mysql, {Pool} from 'promise-mysql'
|
|
import {appConfig} from "./config"
|
|
|
|
let db: Pool
|
|
let poolCreatingPromise = mysql.createPool({
|
|
host: appConfig.dbHost,
|
|
user: appConfig.dbName,
|
|
password: appConfig.dbPassword,
|
|
database: appConfig.dbName
|
|
}).then(value => {
|
|
db = value
|
|
console.log('Pool created.')
|
|
}).error(error => {
|
|
console.error(error)
|
|
console.error('无法连线到资料库')
|
|
process.exit(-1)
|
|
})
|
|
export {db}
|
|
|
|
// let redisClient = redis.createClient({
|
|
// host: appConfig.redisHost,
|
|
// port: appConfig.redisPort
|
|
// })
|
|
// redisClient.on('error', errors => {
|
|
// console.error(errors)
|
|
// })
|
|
// export let redisGet = promisify(redisClient.get).bind(redisClient)
|
|
// export let redisSet = promisify(redisClient.set).bind(redisClient)
|
|
|
|
export function getPoolCreatingPromise() {
|
|
return poolCreatingPromise
|
|
}
|
|
|
|
export const resultJson = {
|
|
success(data: any) {
|
|
return <IResultJson>{
|
|
status: true,
|
|
data: data
|
|
}
|
|
},
|
|
error(data: any) {
|
|
return <IResultJson>{
|
|
status: false,
|
|
data: data
|
|
}
|
|
}
|
|
}
|
|
|
|
export function hasValidationErrors(req: express.Request, res: express.Response) {
|
|
let errors = validationResult(req)
|
|
if (!errors.isEmpty()) {
|
|
res.json(resultJson.error(errors.array()))
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
export function getAxiosInstance() {
|
|
let instance = axios.create({
|
|
headers: {
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0'
|
|
},
|
|
validateStatus: status => true,
|
|
withCredentials: true
|
|
})
|
|
axiosCookieJarSupport(instance)
|
|
instance.defaults.jar = new tough.CookieJar()
|
|
return instance
|
|
}
|
|
|
|
export function getTimestampInSeconds() {
|
|
return Math.floor(Date.now() / 1000)
|
|
}
|