-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (61 loc) · 1.91 KB
/
index.js
File metadata and controls
70 lines (61 loc) · 1.91 KB
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
module.exports = {
init: ({ keystone }) => {
const register = keystone.List.prototype.register
keystone.List.prototype.register = function () {
const List = this
const isSingleton = List.options.singleton
// Only do this if the `singleton` option is set:
if (isSingleton) {
// Get the list name, and a human-readable name
const listName = List.key
const prettyName = listName
.split('')
.map(letter =>
(letter.toUpperCase() === letter)
? ' ' + letter
: letter
)
.join('')
.trim()
// Automatically name the item
List.add({
singleton__name: {
type: String,
required: true,
default: prettyName,
hidden: true
}
})
// Map `singleton__name` to KeystoneJS name
List.options.map = List.options.map || {}
List.options.map.name = List.options.map.name || 'singleton__name'
// Disallow creation and removal
List.options.nocreate = true
List.options.nodelete = true
// Keep label singular by default
List.options.label = List.options.label || prettyName
// Register the singleton
register.apply(this)
// Attempt to create item, if none already exist
const Model = keystone.list(listName).model
Model.count()
.lean()
.exec()
.then(count => {
if (count === 0) {
console.info(`SINGLETON: Creating '${listName}'...`)
return Model.create({})
} else {
return Promise.resolve(undefined)
}
})
.catch(reason => {
console.error(`SINGLETON: Could not create '${listName}'.`)
})
} else {
// Register the list
register.apply(this)
}
}
}
}