const uuid = require('./lib-uuid-random')
class Repo {
static findMany(ids) {
return Promise.all(ids.map(Repo.find))
}
static async find(id) {
const REPO_HUNT = new EdgeKV({namespace: 'repo_hunt'})
const persisted = await REPO_HUNT.get(`repos:${id}`)
const repo = JSON.parse(persisted)
return persisted ? new Repo({ ...repo }) : null
}
constructor({ id, description, name, submitted_at, url }) {
if (!name) {
throw new Error(`Missing name in data`)
}
try {
const urlObj = new URL(url)
const whitelist = ['github.com', 'gitlab.com']
if (!whitelist.some(valid => urlObj.host.toLowerCase().includes(valid))) {
throw new Error('The URL provided is not a repository')
}
} catch (err) {
throw new Error('The URL provided is not valid')
}
this.id = id || uuid()
this.description = description
this.name = name
this.submitted_at = submitted_at || Number(new Date())
this.url = url
}
save() {
const REPO_HUNT = new EdgeKV({namespace: 'repo_hunt'})
return REPO_HUNT.put(`repos:${this.id}`, JSON.stringify(this), {expiration: Math.floor(new Date().getTime()/1000)+60*60*24*29})
}
}
export default Repo