Commit 5bca472d authored by rockyl's avatar rockyl

init3

parent 53f9a180
...@@ -9,6 +9,7 @@ const ali_oss_duiba_1 = require("ali-oss-duiba"); ...@@ -9,6 +9,7 @@ const ali_oss_duiba_1 = require("ali-oss-duiba");
const objectHash = require("object-hash"); const objectHash = require("object-hash");
const path = require("path"); const path = require("path");
const fs = require("fs-extra"); const fs = require("fs-extra");
const redis_1 = require("./redis");
const TYPE_DATA_URL = 'text/dataurl'; const TYPE_DATA_URL = 'text/dataurl';
const acceptTypes = ['image/png', 'image/jpeg', TYPE_DATA_URL]; const acceptTypes = ['image/png', 'image/jpeg', TYPE_DATA_URL];
function applyApi(server) { function applyApi(server) {
...@@ -34,52 +35,71 @@ async function tinify(req, res, next) { ...@@ -34,52 +35,71 @@ async function tinify(req, res, next) {
msg: 'file not exists' msg: 'file not exists'
}); });
} }
else if (fileCount === 1) { else {
const [file] = inputs; const needUpdateHashMap = {};
const result = await tinifyOnce(file, type, cdnRoot); if (fileCount === 1) {
if (typeof result === 'string') { const [input] = inputs;
if (cdnRoot && input.url) {
res.send({
code: 0,
data: input.url
});
}
else {
const result = await tinifyOnce(input, type, cdnRoot);
if (typeof result === 'string') {
needUpdateHashMap[input.hash] = result;
res.send({
code: 0,
data: result
});
}
else if (Buffer.isBuffer(result)) {
res.sendRaw(result, {
'Content-Type': input.type,
});
}
else {
logger_1.default.error('/tinify', 'compress failed', result.message);
res.send({
code: 3,
msg: 'compress failed'
});
}
}
}
else if (cdnRoot) {
const result = await Promise.all(inputs.map(input => tinifyOnce(input, type, cdnRoot)
.then(result => {
if (result) {
needUpdateHashMap[input.hash] = result;
}
else {
result = input.url;
}
if (typeof result === 'string') {
return {
key: input.key,
url: result,
};
}
})));
const data = {};
for (let item of result) {
data[item.key] = item.url;
}
res.send({ res.send({
code: 0, code: 0,
data: result data,
});
}
else if (Buffer.isBuffer(result)) {
res.sendRaw(result, {
'Content-Type': file.type,
}); });
} }
else { else {
logger_1.default.error('/tinify', 'compress failed', result.message);
res.send({ res.send({
code: 3, code: 2,
msg: 'compress failed' msg: 'specify cdnRoot when multi files'
}); });
} }
} await (0, redis_1.setUrlToCache)(needUpdateHashMap);
else if (cdnRoot) {
const result = await Promise.all(inputs.map(file => tinifyOnce(file, type, cdnRoot)
.then(result => {
if (typeof result === 'string') {
return {
key: file.key,
url: result,
};
}
})));
const data = {};
for (let item of result) {
data[item.key] = item.url;
}
res.send({
code: 0,
data,
});
}
else {
res.send({
code: 2,
msg: 'specify cdnRoot when multi files'
});
} }
return next(); return next();
} }
...@@ -114,16 +134,28 @@ async function prepareInputs(req) { ...@@ -114,16 +134,28 @@ async function prepareInputs(req) {
key, key,
extname, extname,
buffer, buffer,
hash: objectHash(buffer),
}; };
inputs.push(input); inputs.push(input);
} }
const hashs = inputs.map(input => input.hash);
const urls = await (0, redis_1.getUrlFromCache)(hashs);
for (let i = 0; i < inputs.length; i++) {
const input = inputs[i];
if (urls[i]) {
input.url = urls[i];
}
}
return inputs; return inputs;
} }
async function tinifyOnce(file, type, cdnRoot) { async function tinifyOnce(input, type, cdnRoot) {
try { try {
const buffer = await (0, compress_1.compressImage)(file.buffer, type); if (input.url) {
return;
}
const buffer = await (0, compress_1.compressImage)(input.buffer, type);
if (cdnRoot) { if (cdnRoot) {
const cdnPath = path.join(cdnRoot, objectHash(buffer) + file.extname); const cdnPath = path.join(cdnRoot, objectHash(buffer) + input.extname);
return (0, ali_oss_duiba_1.uploadFile)(buffer, cdnPath); return (0, ali_oss_duiba_1.uploadFile)(buffer, cdnPath);
} }
else { else {
......
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAEH,qCAA6B;AAC7B,yCAAwC;AACxC,iDAAwC;AACxC,0CAAyC;AACzC,6BAA4B;AAC5B,+BAA8B;AAE9B,MAAM,aAAa,GAAG,cAAc,CAAA;AACpC,MAAM,WAAW,GAAG,CAAC,WAAW,EAAE,YAAY,EAAE,aAAa,CAAC,CAAA;AAE9D,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AC,CAAA;KAClB;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAC7C,MAAM,IAAI,GAAG,MAAM,IAAA,uBAAe,EAAC,KAAK,CAAC,CAAA;IACzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACvC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;QACvB,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE;YACZ,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;SACnB;KACD;IAED,OAAO,MAAM,CAAA;AACd,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO;IAC7C,IAAI;QACH,IAAI,KAAK,CAAC,GAAG,EAAE;YACd,OAAM;SACN;QACD,MAAM,MAAM,GAAG,MAAM,IAAA,wBAAa,EAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;QACtD,IAAI,OAAO,EAAE;YACZ,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,CAAA;YACtE,OAAO,IAAA,0BAAU,EAAC,MAAM,EAAE,OAAO,CAAC,CAAA;SAClC;aAAM;YACN,OAAO,MAAM,CAAA;SACb;KACD;IAAC,OAAO,CAAC,EAAE;QACX,OAAO,CAAC,CAAA;KACR;AACF,CAAC"}
\ No newline at end of file \ No newline at end of file
...@@ -11,6 +11,7 @@ const config = require("config"); ...@@ -11,6 +11,7 @@ const config = require("config");
const api_1 = require("./api"); const api_1 = require("./api");
const ali_oss_duiba_1 = require("ali-oss-duiba"); const ali_oss_duiba_1 = require("ali-oss-duiba");
const cors_1 = require("./cors"); const cors_1 = require("./cors");
const redis_1 = require("./redis");
let eureka; let eureka;
const server = restify.createServer({ const server = restify.createServer({
name: 'tiny-image', name: 'tiny-image',
...@@ -40,13 +41,16 @@ process.on("SIGTERM", () => { ...@@ -40,13 +41,16 @@ process.on("SIGTERM", () => {
async function start() { async function start() {
await (0, remote_configs_1.prepare)(); await (0, remote_configs_1.prepare)();
const ossConfigs = (0, remote_configs_1.getConfigs)({ name: `apollo.oss.duiba.accessId`, alias: 'accessId' }, { name: `apollo.oss.duiba.accessKey`, alias: 'accessKey' }, { name: `apollo.oss.duiba.bucketName`, alias: 'bucketName' }); const ossConfigs = (0, remote_configs_1.getConfigs)({ name: `apollo.oss.duiba.accessId`, alias: 'accessId' }, { name: `apollo.oss.duiba.accessKey`, alias: 'accessKey' }, { name: `apollo.oss.duiba.bucketName`, alias: 'bucketName' });
logger_1.default.info('got oss configs:', ossConfigs); logger_1.default.info('got oss configs:\n', ossConfigs);
const redisConfigs = (0, remote_configs_1.getConfigs)({ name: `apollo.redis.duiba-tiny-image-node.host`, alias: 'host' }, { name: `apollo.redis.duiba-tiny-image-node.port`, alias: 'port' }, { name: `apollo.redis.duiba-tiny-image-node.password`, alias: 'password' });
logger_1.default.info('got redis configs:\n', redisConfigs);
(0, ali_oss_duiba_1.setup)({ (0, ali_oss_duiba_1.setup)({
accessKeyId: ossConfigs.accessId, accessKeyId: ossConfigs.accessId,
accessKeySecret: ossConfigs.accessKey, accessKeySecret: ossConfigs.accessKey,
bucket: ossConfigs.bucketName, bucket: ossConfigs.bucketName,
region: 'oss-cn-hangzhou', region: 'oss-cn-hangzhou',
}); });
await (0, redis_1.prepareRedis)(redisConfigs);
const port = config.get('PORT'); const port = config.get('PORT');
server.listen(port, async function () { server.listen(port, async function () {
if (process.env.NODE_ENV) { if (process.env.NODE_ENV) {
......
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA;;GAEG;AACH,qDAA6E;AAE7E,MAAM,OAAO,GAAG,OAAO,CAAC,SAAS,CA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/B,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK;QACxB,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE;YACzB,IAAI;gBACH,MAAM,GAAG,MAAM,IAAA,wBAAe,EAAC,IAAI,CAAC,CAAA;gBACpC,gBAAM,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAA;aACtC;YAAC,OAAO,CAAC,EAAE;gBACX,gBAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;aACpB;SACD;QACD,gBAAM,CAAC,IAAI,CAAC,oBAAoB,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,CAAA;IAC3D,CAAC,CAAC,CAAA;AACH,CAAC;AAED,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IACjB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;IACd,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AAChB,CAAC,CAAC,CAAA"}
\ No newline at end of file \ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setUrlToCache = exports.getUrlFromCache = exports.prepareRedis = exports.redisClient = void 0;
const redis_1 = require("redis");
const logger_1 = require("./logger");
function prepareRedis(configs) {
const { host, port, password, db = 11 } = configs;
exports.redisClient = (0, redis_1.createClient)(port, host, {
db,
});
exports.redisClient.on('error', function (err) {
logger_1.default.info('redis error:', err);
});
return new Promise((resolve, reject) => {
exports.redisClient.auth(password, function (err, reply) {
if (err) {
reject(err);
}
else {
resolve(reply);
}
});
});
}
exports.prepareRedis = prepareRedis;
function getUrlFromCache(hashs, ns = 'default') {
const nsHashs = hashs.map(hash => ns + ':' + hash);
return new Promise((resolve, reject) => {
exports.redisClient.mget(nsHashs, function (err, replies) {
if (err) {
reject(err);
}
else {
resolve(replies);
}
});
});
}
exports.getUrlFromCache = getUrlFromCache;
function setUrlToCache(data, ns = 'default') {
return new Promise((resolve, reject) => {
const entries = Object.entries(data);
if (entries.length > 0) {
let kvs = [];
entries.forEach(([key, value]) => {
kvs.push(ns + ':' + key, value);
});
exports.redisClient.mset(kvs, function (err, success) {
if (err) {
reject(err);
}
else {
resolve(true);
}
});
}
else {
resolve(false);
}
});
}
exports.setUrlToCache = setUrlToCache;
//# sourceMappingURL=redis.js.map
\ No newline at end of file
{"version":3,"file":"redis.js","sourceRoot":"","sources":["../src/redis.ts"],"names":[],"mappings":";;;AAAA,iCAA+C;AAC/C,qCAA6B;AAI7B,SAAgB,YAAY,CAAC,OAAO;IACnC,MAAM,EAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,EAAC,GAAG,OAAO,CAAA;IAC/C,mBAAW,GAAG,IAAA,oBAAY,EAAC,IAAI,EAAE,IAAI,EAAE;QACtC,EAAE;KACF,CAAC,CAAA;IACF,mBAAW,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG;QACpC,gBAAM,CAAC,IAAI,CAAC,cAAc,EAAE,GAAG,CAAC,CAAA;IACjC,CAAC,CAAC,CAAA;IAEF,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,mBAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,UAAU,GAAG,EAAE,KAAK;YAC9C,IAAI,GAAG,EAAE;gBACR,MAAM,CAAC,GAAG,CAAC,CAAA;aACX;iBAAM;gBACN,OAAO,CAAC,KAAK,CAAC,CAAA;aACd;QACF,CAAC,CAAC,CAAA;IACH,CAAC,CAAC,CAAA;AACH,CAAC;AAlBD,oCAkBC;AAED,SAAgB,eAAe,CAAC,KAAe,EAAE,KAAa,SAAS;IACtE,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,GAAG,GAAG,GAAG,IAAI,CAAC,CAAA;IAElD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,mBAAW,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,EAAE,OAAO;YAC/C,IAAI,GAAG,EAAE;gBACR,MAAM,CAAC,GAAG,CAAC,CAAA;aACX;iBAAM;gBACN,OAAO,CAAC,OAAO,CAAC,CAAA;aAChB;QACF,CAAC,CAAC,CAAA;IACH,CAAC,CAAC,CAAA;AACH,CAAC;AAZD,0CAYC;AAED,SAAgB,aAAa,CAAC,IAAS,EAAE,KAAa,SAAS;IAC9D,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;QACpC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;YACvB,IAAI,GAAG,GAAa,EAAE,CAAA;YACtB,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBAChC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,GAAG,GAAG,GAAG,EAAE,KAAe,CAAC,CAAA;YAC1C,CAAC,CAAC,CAAA;YACF,mBAAW,CAAC,IAAI,CAAC,GAAG,EAAE,UAAU,GAAG,EAAE,OAAO;gBAC3C,IAAI,GAAG,EAAE;oBACR,MAAM,CAAC,GAAG,CAAC,CAAA;iBACX;qBAAM;oBACN,OAAO,CAAC,IAAI,CAAC,CAAA;iBACb;YACF,CAAC,CAAC,CAAA;SACF;aAAM;YACN,OAAO,CAAC,KAAK,CAAC,CAAA;SACd;IACF,CAAC,CAAC,CAAA;AACH,CAAC;AAnBD,sCAmBC"}
\ No newline at end of file
{
"local": {
"host": "http://localhost:8093"
},
"dev": {
"host": "http://tinify.duibadev.com.cn"
},
"prod": {
"host": "http://tinify.duiba.com.cn"
}
}
...@@ -38,3 +38,8 @@ Content-Type: image/png ...@@ -38,3 +38,8 @@ Content-Type: image/png
< /Users/rockyl/Pictures/烽火台-logo.png < /Users/rockyl/Pictures/烽火台-logo.png
--WebAppBoundary-- --WebAppBoundary--
Content-Disposition: form-data; name="file4"; filename="aaa.jpg"
Content-Type: image/jpeg
< /Users/rockyl/Pictures/750966451939330.jpg
--WebAppBoundary--
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
"start": "node dist/index.js" "start": "node dist/index.js"
}, },
"dependencies": { "dependencies": {
"ali-oss-duiba": "^1.0.12", "ali-oss-duiba": "^1.0.14",
"config": "^3.3.6", "config": "^3.3.6",
"eureka-client-ts": "^0.2.10", "eureka-client-ts": "^0.2.10",
"fs-extra": "^8.1.0", "fs-extra": "^8.1.0",
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
"node-fetch": "2", "node-fetch": "2",
"node-tinify": "^1.0.4", "node-tinify": "^1.0.4",
"object-hash": "^2.2.0", "object-hash": "^2.2.0",
"redis": "^3.1.2",
"restify": "^8.5.1" "restify": "^8.5.1"
}, },
"devDependencies": { "devDependencies": {
...@@ -30,6 +31,7 @@ ...@@ -30,6 +31,7 @@
"@types/imagemin": "^8.0.0", "@types/imagemin": "^8.0.0",
"@types/node-fetch": "2", "@types/node-fetch": "2",
"@types/object-hash": "^2.2.1", "@types/object-hash": "^2.2.1",
"@types/redis": "^2.8.32",
"@types/restify": "^8.4.2", "@types/restify": "^8.4.2",
"rollup-plugin-progress": "^1.1.1", "rollup-plugin-progress": "^1.1.1",
"typescript": "^4.4.4" "typescript": "^4.4.4"
......
...@@ -8,6 +8,7 @@ import {uploadFile} from 'ali-oss-duiba' ...@@ -8,6 +8,7 @@ import {uploadFile} from 'ali-oss-duiba'
import * as objectHash from 'object-hash' import * as objectHash from 'object-hash'
import * as path from 'path' import * as path from 'path'
import * as fs from 'fs-extra' import * as fs from 'fs-extra'
import {getUrlFromCache, setUrlToCache} from "./redis";
const TYPE_DATA_URL = 'text/dataurl' const TYPE_DATA_URL = 'text/dataurl'
const acceptTypes = ['image/png', 'image/jpeg', TYPE_DATA_URL] const acceptTypes = ['image/png', 'image/jpeg', TYPE_DATA_URL]
...@@ -37,49 +38,66 @@ async function tinify(req, res, next) { ...@@ -37,49 +38,66 @@ async function tinify(req, res, next) {
code: 1, code: 1,
msg: 'file not exists' msg: 'file not exists'
}) })
} else if (fileCount === 1) { } else {
const [file] = inputs const needUpdateHashMap = {}
const result = await tinifyOnce(file, type, cdnRoot) if (fileCount === 1) {
if (typeof result === 'string') { const [input] = inputs
if (cdnRoot && input.url) {
res.send({
code: 0,
data: input.url
})
} else {
const result = await tinifyOnce(input, type, cdnRoot)
if (typeof result === 'string') {
needUpdateHashMap[input.hash] = result
res.send({
code: 0,
data: result
})
} else if (Buffer.isBuffer(result)) {
res.sendRaw(result, {
'Content-Type': input.type,
})
} else {
logger.error('/tinify', 'compress failed', result.message)
res.send({
code: 3,
msg: 'compress failed'
})
}
}
} else if (cdnRoot) {
const result = await Promise.all<any>(inputs.map(input => tinifyOnce(input, type, cdnRoot)
.then(result => {
if (result) {
needUpdateHashMap[input.hash] = result
}else{
result = input.url
}
if (typeof result === 'string') {
return {
key: input.key,
url: result,
}
}
})
))
const data = {}
for (let item of result) {
data[item.key] = item.url
}
res.send({ res.send({
code: 0, code: 0,
data: result data,
})
} else if (Buffer.isBuffer(result)) {
res.sendRaw(result, {
'Content-Type': file.type,
}) })
} else { } else {
logger.error('/tinify', 'compress failed', result.message)
res.send({ res.send({
code: 3, code: 2,
msg: 'compress failed' msg: 'specify cdnRoot when multi files'
}) })
} }
} else if (cdnRoot) { await setUrlToCache(needUpdateHashMap)
const result = await Promise.all<any>(inputs.map(file => tinifyOnce(file, type, cdnRoot)
.then(result => {
if (typeof result === 'string') {
return {
key: file.key,
url: result,
}
}
})
))
const data = {}
for (let item of result) {
data[item.key] = item.url
}
res.send({
code: 0,
data,
})
} else {
res.send({
code: 2,
msg: 'specify cdnRoot when multi files'
})
} }
return next() return next()
} }
...@@ -116,17 +134,31 @@ async function prepareInputs(req) { ...@@ -116,17 +134,31 @@ async function prepareInputs(req) {
key, key,
extname, extname,
buffer, buffer,
hash: objectHash(buffer),
} }
inputs.push(input) inputs.push(input)
} }
const hashs = inputs.map(input => input.hash)
const urls = await getUrlFromCache(hashs)
for (let i = 0; i < inputs.length; i++) {
const input = inputs[i]
if (urls[i]) {
input.url = urls[i]
}
}
return inputs return inputs
} }
async function tinifyOnce(file, type, cdnRoot) { async function tinifyOnce(input, type, cdnRoot) {
try { try {
const buffer = await compressImage(file.buffer, type) if (input.url) {
return
}
const buffer = await compressImage(input.buffer, type)
if (cdnRoot) { if (cdnRoot) {
const cdnPath = path.join(cdnRoot, objectHash(buffer) + file.extname) const cdnPath = path.join(cdnRoot, objectHash(buffer) + input.extname)
return uploadFile(buffer, cdnPath) return uploadFile(buffer, cdnPath)
} else { } else {
return buffer return buffer
......
...@@ -10,6 +10,7 @@ import * as config from "config" ...@@ -10,6 +10,7 @@ import * as config from "config"
import applyApi from "./api" import applyApi from "./api"
import {setup as setupOSS} from 'ali-oss-duiba' import {setup as setupOSS} from 'ali-oss-duiba'
import cors from "./cors"; import cors from "./cors";
import {prepareRedis} from "./redis";
let eureka let eureka
...@@ -52,7 +53,14 @@ async function start() { ...@@ -52,7 +53,14 @@ async function start() {
{name: `apollo.oss.duiba.accessKey`, alias: 'accessKey'}, {name: `apollo.oss.duiba.accessKey`, alias: 'accessKey'},
{name: `apollo.oss.duiba.bucketName`, alias: 'bucketName'}, {name: `apollo.oss.duiba.bucketName`, alias: 'bucketName'},
) )
logger.info('got oss configs:', ossConfigs) logger.info('got oss configs:\n', ossConfigs)
const redisConfigs = getConfigs(
{name: `apollo.redis.duiba-tiny-image-node.host`, alias: 'host'},
{name: `apollo.redis.duiba-tiny-image-node.port`, alias: 'port'},
{name: `apollo.redis.duiba-tiny-image-node.password`, alias: 'password'},
)
logger.info('got redis configs:\n', redisConfigs)
setupOSS({ setupOSS({
accessKeyId: ossConfigs.accessId, accessKeyId: ossConfigs.accessId,
...@@ -61,6 +69,8 @@ async function start() { ...@@ -61,6 +69,8 @@ async function start() {
region: 'oss-cn-hangzhou', region: 'oss-cn-hangzhou',
}) })
await prepareRedis(redisConfigs)
const port = config.get('PORT') const port = config.get('PORT')
server.listen(port, async function () { server.listen(port, async function () {
if (process.env.NODE_ENV) { if (process.env.NODE_ENV) {
......
import {createClient, RedisClient} from 'redis'
import logger from "./logger"
export let redisClient: RedisClient
export function prepareRedis(configs) {
const {host, port, password, db = 11} = configs
redisClient = createClient(port, host, {
db,
})
redisClient.on('error', function (err) {
logger.info('redis error:', err)
})
return new Promise((resolve, reject) => {
redisClient.auth(password, function (err, reply) {
if (err) {
reject(err)
} else {
resolve(reply)
}
})
})
}
export function getUrlFromCache(hashs: string[], ns: string = 'default'): Promise<string[]> {
const nsHashs = hashs.map(hash => ns + ':' + hash)
return new Promise((resolve, reject) => {
redisClient.mget(nsHashs, function (err, replies) {
if (err) {
reject(err)
} else {
resolve(replies)
}
})
})
}
export function setUrlToCache(data: any, ns: string = 'default') {
return new Promise((resolve, reject) => {
const entries = Object.entries(data)
if (entries.length > 0) {
let kvs: string[] = []
entries.forEach(([key, value]) => {
kvs.push(ns + ':' + key, value as string)
})
redisClient.mset(kvs, function (err, success) {
if (err) {
reject(err)
} else {
resolve(true)
}
})
} else {
resolve(false)
}
})
}
...@@ -126,6 +126,13 @@ ...@@ -126,6 +126,13 @@
resolved "http://npm.dui88.com:80/@types%2fobject-hash/-/object-hash-2.2.1.tgz#67c169f8f033e0b62abbf81df2d00f4598d540b9" resolved "http://npm.dui88.com:80/@types%2fobject-hash/-/object-hash-2.2.1.tgz#67c169f8f033e0b62abbf81df2d00f4598d540b9"
integrity sha1-Z8Fp+PAz4LYqu/gd8tAPRZjVQLk= integrity sha1-Z8Fp+PAz4LYqu/gd8tAPRZjVQLk=
"@types/redis@^2.8.32":
version "2.8.32"
resolved "http://npm.dui88.com:80/@types%2fredis/-/redis-2.8.32.tgz#1d3430219afbee10f8cfa389dad2571a05ecfb11"
integrity sha1-HTQwIZr77hD4z6OJ2tJXGgXs+xE=
dependencies:
"@types/node" "*"
"@types/restify@^8.4.2": "@types/restify@^8.4.2":
version "8.5.2" version "8.5.2"
resolved "https://registry.yarnpkg.com/@types/restify/-/restify-8.5.2.tgz#e4679d5ee7852f2a123b3e0c92ee1f72515c8a25" resolved "https://registry.yarnpkg.com/@types/restify/-/restify-8.5.2.tgz#e4679d5ee7852f2a123b3e0c92ee1f72515c8a25"
...@@ -172,10 +179,10 @@ ajv@^6.12.3: ...@@ -172,10 +179,10 @@ ajv@^6.12.3:
json-schema-traverse "^0.4.1" json-schema-traverse "^0.4.1"
uri-js "^4.2.2" uri-js "^4.2.2"
ali-oss-duiba@^1.0.12: ali-oss-duiba@^1.0.14:
version "1.0.12" version "1.0.14"
resolved "http://npm.dui88.com:80/ali-oss-duiba/-/ali-oss-duiba-1.0.12.tgz#0e7af073fca7677c1d43123781a05c49d47ab900" resolved "http://npm.dui88.com:80/ali-oss-duiba/-/ali-oss-duiba-1.0.14.tgz#d8e1e3e95d64b1cebe54c51289d587d65f7bae79"
integrity sha512-sUNXqzK4Z5UReCdlEt9z+EsacBfl+eGfNqoswF5o4mqdubYAk7b/eeN5Rh42B8z4yPoJRO0dG8EzRi25YYSMGA== integrity sha512-JSlj7lckJ6AU6e+crMoPT8GK2R+IEsBq9jKqE1v3kV5A278A4QpHrBvkylQuGnHHIUpGERlg+miwYVSd0+r5jg==
dependencies: dependencies:
"@types/ali-oss" "^6.0.8" "@types/ali-oss" "^6.0.8"
ali-oss "^6.15.2" ali-oss "^6.15.2"
...@@ -822,6 +829,11 @@ delayed-stream@~1.0.0: ...@@ -822,6 +829,11 @@ delayed-stream@~1.0.0:
resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk=
denque@^1.5.0:
version "1.5.1"
resolved "http://npm.dui88.com:80/denque/-/denque-1.5.1.tgz#07f670e29c9a78f8faecb2566a1e2c11929c5cbf"
integrity sha1-B/Zw4pyaePj67LJWah4sEZKcXL8=
depd@~1.1.2: depd@~1.1.2:
version "1.1.2" version "1.1.2"
resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9"
...@@ -2781,6 +2793,33 @@ redent@^1.0.0: ...@@ -2781,6 +2793,33 @@ redent@^1.0.0:
indent-string "^2.1.0" indent-string "^2.1.0"
strip-indent "^1.0.1" strip-indent "^1.0.1"
redis-commands@^1.7.0:
version "1.7.0"
resolved "http://npm.dui88.com:80/redis-commands/-/redis-commands-1.7.0.tgz#15a6fea2d58281e27b1cd1acfb4b293e278c3a89"
integrity sha1-Fab+otWCgeJ7HNGs+0spPieMOok=
redis-errors@^1.0.0, redis-errors@^1.2.0:
version "1.2.0"
resolved "http://npm.dui88.com:80/redis-errors/-/redis-errors-1.2.0.tgz#eb62d2adb15e4eaf4610c04afe1529384250abad"
integrity sha1-62LSrbFeTq9GEMBK/hUpOEJQq60=
redis-parser@^3.0.0:
version "3.0.0"
resolved "http://npm.dui88.com:80/redis-parser/-/redis-parser-3.0.0.tgz#b66d828cdcafe6b4b8a428a7def4c6bcac31c8b4"
integrity sha1-tm2CjNyv5rS4pCin3vTGvKwxyLQ=
dependencies:
redis-errors "^1.0.0"
redis@^3.1.2:
version "3.1.2"
resolved "http://npm.dui88.com:80/redis/-/redis-3.1.2.tgz#766851117e80653d23e0ed536254677ab647638c"
integrity sha1-dmhREX6AZT0j4O1TYlRnerZHY4w=
dependencies:
denque "^1.5.0"
redis-commands "^1.7.0"
redis-errors "^1.2.0"
redis-parser "^3.0.0"
repeating@^2.0.0: repeating@^2.0.0:
version "2.0.1" version "2.0.1"
resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda"
......
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