From e0871eeffb2755fd8a93d58fb7d8b5cb7a07c14c Mon Sep 17 00:00:00 2001 From: Ben Allfree Date: Sat, 4 Nov 2023 22:12:30 +0000 Subject: [PATCH] enh: add availability check to API --- src/mothership-app/pb_hooks/src/index.pb.js | 59 ++++++++++++++------- 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/src/mothership-app/pb_hooks/src/index.pb.js b/src/mothership-app/pb_hooks/src/index.pb.js index 00014207..73b236ab 100644 --- a/src/mothership-app/pb_hooks/src/index.pb.js +++ b/src/mothership-app/pb_hooks/src/index.pb.js @@ -1,31 +1,54 @@ onAfterBootstrap((e) => { $app.dao().db().newQuery(`update instances set status='idle'`).execute() - $app - .dao() - .db() - .newQuery(`update invocations set endedAt=datetime('now') where endedAt=''`) - .execute() + // $app + // .dao() + // .db() + // .newQuery(`update invocations set endedAt=datetime('now') where endedAt=''`) + // .execute() }) routerAdd( 'GET', '/api/signup', (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 = (() => { - let i = 0 - while (true) { - i++ - if (i > 100) { - return +new Date() + const name = c.queryParam('name').trim() + if (name) { + if (isAvailable(name)) { + return name } - const slug = random.generate(2).join(`-`) - try { - const record = $app - .dao() - .findFirstRecordByData('instances', 'subdomain', slug) - } catch { - return slug + throw error( + `instanceName`, + `exists`, + `Instance name ${name} is not available.`, + ) + } else { + const random = require(`${__hooks}/random-words.js`) + let i = 0 + while (true) { + i++ + if (i > 100) { + return +new Date() + } + const slug = random.generate(2).join(`-`) + if (isAvailable(slug)) return slug } } })()