feat: wip previews for non-get routes

This commit is contained in:
Your Name 2025-01-21 01:08:54 -05:00
parent ee0b9e597a
commit a23aee5d21
5 changed files with 366 additions and 24 deletions

242
db.js
View file

@ -126,22 +126,61 @@ function createStructure(db, name, userId) {
function createRoute(db, verb, path, structureId, handler) {
path = encodeURI(path);
// add default handler here
const stmt = db.prepare(
"INSERT INTO routes (verb, path, structure_id, handler) VALUES (?, ?, ?, ?)",
"INSERT INTO routes (verb, path, structure_id, handler) VALUES (?, ?, ?, ?)"
);
const info = stmt.run(verb, path, structureId, handler);
return info.lastInsertRowid; // Returns the route_id of the newly created route
const routeId = info.lastInsertRowid; // Get the newly created route ID
if (verb !== 'GET') {
createScaffoldPage(db, routeId);
}
return routeId; // Returns the route_id of the newly created route
}
function getRoutes(db, structureId) {
return db
.prepare("SELECT * from routes where structure_id = ?")
.all(structureId);
const query = `
SELECT
r.*,
sp.id AS scaffold_page_id,
sp.content AS scaffold_page_content,
sp2.id AS scaffold_params_id,
sp2.query_params,
sp2.url_params
FROM routes r
LEFT JOIN scaffold_pages sp ON r.id = sp.route_id
LEFT JOIN scaffold_params sp2 ON r.id = sp2.route_id
WHERE r.structure_id = ?
ORDER BY sp.created_at DESC, sp2.created_at DESC
`;
return db.prepare(query).all(structureId);
}
function getRoute(db, routeId) {
return db.prepare("SELECT * from routes where id = ?").get(routeId);
const query = `
SELECT
r.*,
sp.id AS scaffold_page_id,
sp.content AS scaffold_page_content,
sp2.id AS scaffold_params_id,
sp2.query_params,
sp2.url_params
FROM routes r
LEFT JOIN scaffold_pages sp ON r.id = sp.route_id
LEFT JOIN scaffold_params sp2 ON r.id = sp2.route_id
WHERE r.id = ?
ORDER BY sp.created_at DESC, sp2.created_at DESC
LIMIT 1
`;
return db.prepare(query).get(routeId);
}
function defaultEndpointForRoute(db, routeId) {
}
function updateRoute(db, route) {
@ -334,7 +373,7 @@ function cloneStructure(
).lastInsertRowid;
const dbIds = db
.prepare(`select db_id from structure_dbs where structure_id = ?;`)
.prepare(`SELECT db_id FROM structure_dbs WHERE structure_id = ?;`)
.all(structId);
const toClone = new Set(cloneDbs);
@ -352,7 +391,7 @@ function cloneStructure(
`
INSERT INTO dbs (name, structure_id, library)
SELECT name, ?, library FROM dbs WHERE id = ?;
`,
`,
)
.run(newStructId, db_id).lastInsertRowid;
@ -360,10 +399,10 @@ function cloneStructure(
`
INSERT INTO structure_dbs (db_id, structure_id, alias)
SELECT ?, ?, alias FROM structure_dbs WHERE db_id = ? AND structure_id = ?;
`,
`,
).run(newDb, newStructId, db_id, structId);
db.prepare(`select id from dbs where structure_id = ?`)
db.prepare(`SELECT id FROM dbs WHERE structure_id = ?`)
.all(newStructId)
.map((new_db) => {
const srcPath = path.join(__dirname, "dbs", `${db_id}.sqlite`);
@ -373,6 +412,7 @@ function cloneStructure(
fs.copyFileSync(srcPath + "-wal", destPath + "-wal");
});
}
for (let db_id of toAlias) {
db.prepare(
`
@ -382,18 +422,42 @@ function cloneStructure(
).run(newStructId, structId, db_id);
}
// Clone templates
const cloneTemplates = db.prepare(`
INSERT INTO templates (name, content, structure_id, test_object, engine)
SELECT name, content, ?, test_object, engine FROM templates WHERE structure_id = ?;
`);
cloneTemplates.run(newStructId, structId);
// Clone routes
const cloneRoutes = db.prepare(`
INSERT INTO routes (verb, path, structure_id, handler)
SELECT verb, path, ?, handler FROM routes WHERE structure_id = ?;
`);
cloneRoutes.run(newStructId, structId);
// Clone scaffold pages
const cloneScaffoldPages = db.prepare(`
INSERT INTO scaffold_pages (route_id, content, created_at)
SELECT newRoutes.id, sp.content, sp.created_at
FROM scaffold_pages sp
JOIN routes oldRoutes ON sp.route_id = oldRoutes.id
JOIN routes newRoutes ON oldRoutes.path = newRoutes.path AND oldRoutes.verb = newRoutes.verb
WHERE oldRoutes.structure_id = ? AND newRoutes.structure_id = ?;
`);
cloneScaffoldPages.run(structId, newStructId);
// Clone scaffold params
const cloneScaffoldParams = db.prepare(`
INSERT INTO scaffold_params (route_id, query_params, url_params, created_at)
SELECT newRoutes.id, sp.query_params, sp.url_params, sp.created_at
FROM scaffold_params sp
JOIN routes oldRoutes ON sp.route_id = oldRoutes.id
JOIN routes newRoutes ON oldRoutes.path = newRoutes.path AND oldRoutes.verb = newRoutes.verb
WHERE oldRoutes.structure_id = ? AND newRoutes.structure_id = ?;
`);
cloneScaffoldParams.run(structId, newStructId);
return newStructId;
});
@ -432,6 +496,158 @@ function getMostRecentLogIdByRoute(db, routeId) {
return result ? result.id : 0;
}
function buildScaffoldUrl(endpoint, urlParams, queryString) {
let populatedUrl = endpoint.replace(/:([^/]+)/g, () => urlParams.shift() || '');
return queryString ? `${populatedUrl}?${queryString}` : populatedUrl;
}
function createScaffoldPage(db, routeId, content=null) {
if (!content) {
const route = getRoute(db, routeId)
const endpoint = buildScaffoldUrl(route.path, route.url_params, route.query_params);
content = getDefaultScaffoldContentByVerb(endpoint, route.verb);
console.log("gabga", content, route, endpoint)
}
console.log(content, "content")
const stmt = db.prepare(
"INSERT INTO scaffold_pages (route_id, content) VALUES (?, ?)"
);
const info = stmt.run(routeId, content);
return info.lastInsertRowid; // Returns the scaffold_page id of the newly created scaffold page
}
function getLatestScaffoldPage(db, routeId) {
const stmt = db.prepare(
"SELECT * FROM scaffold_pages WHERE route_id = ? ORDER BY created_at DESC LIMIT 1"
);
return stmt.get(routeId);
}
function updateScaffoldPage(db, scaffoldPage) {
const fields = ["content"];
const values = fields.map((field) => scaffoldPage[field]);
const placeholders = fields.map((field) => `${field} = ?`).join(", ");
console.log(scaffoldPage, "gabababab")
const sql = `UPDATE scaffold_pages SET ${placeholders} WHERE id = ?`;
values.push(scaffoldPage.id); // Add scaffoldPageId to the end for the WHERE clause
const info = db.prepare(sql).run(...values);
console.log(info.changes)
return info.changes > 0; // Returns true if a row was updated, false otherwise
}
function generatePostForm(endpoint) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test POST Request</title>
<script src="https://unpkg.com/htmx.org@1.9.2"></script>
</head>
<body>
<h1>Test POST Request</h1>
<form action="<%= it.route("${endpoint}") %>" method="POST">
<!-- Add your form fields here to test post requests. -->
<label for="testField">Test Field:</label>
<input type="text" id="testField" name="testField" required>
<button type="submit">Submit</button>
</form>
<!-- Add any divs for hx-swaps anywhere on the page. -->
<div id="result" hx-swap="innerHTML"></div>
</body>
</html>
`;
}
function generateModifyForm(endpoint, verb) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test ${verb} Request</title>
<script src="https://unpkg.com/htmx.org@1.9.2"></script>
</head>
<body>
<h1>Test ${verb} Request</h1>
<form action="<%= it.route(${endpoint}) %>" method="${verb}">
<!-- Add your form fields here to test ${verb.toLowerCase()} requests. -->
<label for="testField">Test Field:</label>
<input type="text" id="testField" name="testField" required>
<button type="submit">${verb}</button>
</form>
<!-- Add any divs for hx-swaps anywhere on the page. -->
<div id="result" hx-swap="innerHTML"></div>
</body>
</html>
`;
}
function generateWSPage(endpoint) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test WebSocket</title>
</head>
<body>
<h1>Test WebSocket Connection</h1>
<input type="text" id="wsMessage" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<div id="wsOutput"></div>
<script>
const ws = new WebSocket('<%= it.route("${endpoint}") %>');
ws.onopen = () => {
document.getElementById('wsOutput').innerHTML += '<p>Connected to WebSocket</p>';
};
ws.onmessage = (event) => {
document.getElementById('wsOutput').innerHTML += '<p>Received: ' + event.data + '</p>';
};
ws.onclose = () => {
document.getElementById('wsOutput').innerHTML += '<p>WebSocket connection closed</p>';
};
function sendMessage() {
const message = document.getElementById('wsMessage').value;
ws.send(message);
document.getElementById('wsOutput').innerHTML += '<p>Sent: ' + message + '</p>';
}
</script>
</body>
</html>
`;
}
function getDefaultScaffoldContentByVerb(url, verb) {
if (verb == "POST") {
return generatePostForm(url);
}
else if (verb == "PUT" || verb == "DELETE") {
return generateModifyForm(url, verb);
}
else if (verb == "WS") {
return generateWSPage(url);
}
}
module.exports = {
db,
applyMigrations,
@ -445,6 +661,7 @@ module.exports = {
createRoute,
getRoutes,
getRoute,
buildScaffoldUrl,
updateRoute,
updateDb,
updateStruct,
@ -467,4 +684,7 @@ module.exports = {
getLogsByRoute,
getNewLogsByRoute,
getMostRecentLogIdByRoute,
createScaffoldPage,
getLatestScaffoldPage,
updateScaffoldPage
};