enh: add availability check to API

This commit is contained in:
Ben Allfree 2023-11-04 22:12:30 +00:00
parent a662a9bc7b
commit e0871eeffb

View File

@ -1,18 +1,46 @@
onAfterBootstrap((e) => { onAfterBootstrap((e) => {
$app.dao().db().newQuery(`update instances set status='idle'`).execute() $app.dao().db().newQuery(`update instances set status='idle'`).execute()
$app // $app
.dao() // .dao()
.db() // .db()
.newQuery(`update invocations set endedAt=datetime('now') where endedAt=''`) // .newQuery(`update invocations set endedAt=datetime('now') where endedAt=''`)
.execute() // .execute()
}) })
routerAdd( routerAdd(
'GET', 'GET',
'/api/signup', '/api/signup',
(c) => { (c) => {
const random = require(`${__hooks}/random-words.js`) const isAvailable = (slug) => {
try {
const record = $app
.dao()
.findFirstRecordByData('instances', 'subdomain', slug)
return false
} catch {
return true
}
}
const error = (fieldName, slug, description, extra) =>
new ApiError(500, description, {
[fieldName]: new ValidationError(slug, description),
...extra,
})
const instanceName = (() => { const instanceName = (() => {
const name = c.queryParam('name').trim()
if (name) {
if (isAvailable(name)) {
return name
}
throw error(
`instanceName`,
`exists`,
`Instance name ${name} is not available.`,
)
} else {
const random = require(`${__hooks}/random-words.js`)
let i = 0 let i = 0
while (true) { while (true) {
i++ i++
@ -20,12 +48,7 @@ routerAdd(
return +new Date() return +new Date()
} }
const slug = random.generate(2).join(`-`) const slug = random.generate(2).join(`-`)
try { if (isAvailable(slug)) return slug
const record = $app
.dao()
.findFirstRecordByData('instances', 'subdomain', slug)
} catch {
return slug
} }
} }
})() })()