/
index.js
58 lines (53 loc) · 1.63 KB
/
index.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
const knex = appRequire('init/knex').knex;
const getTags = async (type, key) => {
if(key) {
return knex('tag').select(['name']).where({ type, key }).then(success => success.map(m => m.name));
}
return knex('tag').select(['name']).where({ type }).groupBy('name').then(success => success.map(m => m.name));
};
const setTags = async (type, key, tags) => {
const currentTags = await knex('tag').select(['id', 'name']).where({ type, key });
for(const ct of currentTags) {
if(!tags.includes(ct.name)) {
await knex('tag').delete().where({ id: ct.id });
}
}
const newTags = tags.filter(f => {
return !currentTags.map(m => m.name).includes(f);
}).map(tag => {
return {
type, key, name: tag,
};
});
if(newTags.length) {
await knex('tag').insert(newTags);
}
};
const addTags = async (type, key, tags) => {
const currentTags = await knex('tag').select(['id', 'name']).where({ type, key });
const newTags = tags.filter(f => {
return !currentTags.map(m => m.name).includes(f);
}).map(tag => {
return {
type, key, name: tag,
};
});
if(newTags.length) {
await knex('tag').insert(newTags);
}
};
const delTags = async (type, key, tags) => {
// const currentTags = await knex('tag').select(['id', 'name']).where({ type, key });
// for(const ct of currentTags) {
// if(!tags.includes(ct.name)) {
// await knex('tag').delete().where({ id: ct.id });
// }
// }
for(const tag of tags) {
await knex('tag').delete().where({ type, key, name: tag });
}
};
exports.getTags = getTags;
exports.setTags = setTags;
exports.addTags = addTags;
exports.delTags = delTags;