This repository has been archived by the owner on Apr 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProject.js
89 lines (71 loc) · 2.13 KB
/
Project.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const path = require("path");
const fs = require("mz/fs");
const crypto = require("mz/crypto");
const yup = require("yup");
const execa = require("execa");
const Minimatch = require("minimatch").Minimatch;
const redis = require("./redis");
const Server = require("../lib/Server");
const github = require("../.github");
const deploy = require("./deploy");
const schema = yup.object().shape({
name: yup.string().required(),
repo: yup.string().required(),
servers: yup.array().of(yup.number().positive().integer()).min(0).required(),
directory: yup.string().required(),
active: yup.bool().required(),
pushSecret: yup.string().required(),
id: yup.number().strip()
});
class Project {
constructor(project) {
Object.assign(this, project);
}
async save() {
if(this.id == undefined) {
this.id = await redis.incr("project:id");
}
const obj = schema.cast(Object.assign({}, this));
await schema.validate(obj);
await redis.multi()
.sadd("project:instances", this.id)
.zremrangebyscore("project:repos", this.id, this.id)
.zadd("project:repos", this.id, obj.repo)
.set(`project:instance:${this.id}`, JSON.stringify(obj))
.exec();
}
async deploy() {
return deploy.apply(this, arguments);
}
static async create(input) {
const project = new Project(input);
project.pushSecret = (await crypto.randomBytes(32)).toString("base64").slice(0, -1);
await project.save();
return project;
}
static async find(id) {
const json = await redis.get(`project:instance:${id}`);
if(typeof json !== "string") {
throw new Error(`Project ${id} does not exist`);
}
const project = JSON.parse(json);
project.id = id;
return new Project(project);
}
static async findByRepo(repo) {
const id = await redis.zscore("project:repos", repo);
return await Project.find(id);
}
static async list() {
const ids = await redis.smembers("project:instances");
return await Promise.all(ids.map(id => Project.find(id)));
}
static async delete(id) {
await redis.multi()
.srem("project:instances", id)
.zremrangebyscore("project:repos", this.id, this.id)
.del(`project:instance:${id}`)
.exec();
}
};
module.exports = Project;