hostr/lib/hostr-id.js

27 lines
632 B
JavaScript
Raw Normal View History

2016-06-19 10:14:47 -07:00
import models from '../models';
2015-07-09 23:01:43 +01:00
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
function randomID() {
let rand = '';
for (let i = 0; i < 12; i++) {
rand += chars.charAt(Math.floor((Math.random() * chars.length)));
}
return rand;
}
2018-06-02 15:50:39 +00:00
async function checkId(Files, fileId, attempts) {
2015-07-09 23:01:43 +01:00
if (attempts > 10) {
return false;
}
2018-06-02 15:50:39 +00:00
const file = await models.file.findById(fileId);
2015-08-23 22:12:32 +01:00
if (file === null) {
2015-07-09 23:01:43 +01:00
return fileId;
}
2015-08-23 22:12:32 +01:00
return checkId(randomID(), ++attempts); // eslint-disable-line no-param-reassign
2015-07-09 23:01:43 +01:00
}
2018-06-02 15:50:39 +00:00
export default function (Files) {
return checkId(Files, randomID(), 0);
2015-07-09 23:01:43 +01:00
}