From 1f05df68eb8482c98f139317b97e22a64d8d18d5 Mon Sep 17 00:00:00 2001 From: KernelDeimos Date: Tue, 4 Mar 2025 13:00:01 -0500 Subject: [PATCH] dev: add threads module for puter.js --- src/puter-js/src/index.js | 2 ++ src/puter-js/src/modules/Threads.js | 47 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/puter-js/src/modules/Threads.js diff --git a/src/puter-js/src/index.js b/src/puter-js/src/index.js index 10d4a4762..be240505f 100644 --- a/src/puter-js/src/index.js +++ b/src/puter-js/src/index.js @@ -25,6 +25,7 @@ import { PWispHandler } from './modules/networking/PWispHandler.js'; import { make_http_api } from './lib/http.js'; import Exec from './modules/Exec.js'; import Convert from './modules/Convert.js'; +import Threads from './modules/Threads.js'; // TODO: This is for a safe-guard below; we should check if we can // generalize this behavior rather than hard-coding it. @@ -98,6 +99,7 @@ window.puter = (function() { this.registerModule('apps', Apps); this.registerModule('ai', AI); this.registerModule('kv', KV); + this.registerModule('threads', Threads); this.registerModule('drivers', Drivers); this.registerModule('debug', Debug); this.registerModule('exec', Exec); diff --git a/src/puter-js/src/modules/Threads.js b/src/puter-js/src/modules/Threads.js new file mode 100644 index 000000000..bf899cde2 --- /dev/null +++ b/src/puter-js/src/modules/Threads.js @@ -0,0 +1,47 @@ +export default class Threads { + setAuthToken (authToken) { + this.authToken = authToken; + } + setAPIOrigin (APIOrigin) { + this.APIOrigin = APIOrigin; + } + async req_ (method, route, body) { + const resp = await fetch( + this.APIOrigin + route, { + method, + headers: { + Authorization: `Bearer ${this.authToken}`, + ...(body ? { 'Content-Type': 'application/json' } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + } + ); + return await resp.json(); + } + + async create (spec, parent) { + if ( typeof spec === 'string' ) spec = { text: spec }; + await this.req_('POST', '/threads/create', { + ...spec, + ...(parent ? { parent } : {}), + }); + } + + async edit (uid, spec = {}) { + if ( typeof spec === 'string' ) spec = { text: spec }; + await this.req_('PUT', '/threads/edit/' + encodeURIComponent(uid), { + ...spec, + }); + } + + async delete (uid) { + await this.req_('DELETE', '/threads/' + encodeURIComponent(uid)); + } + + async list (uid, page, options) { + await this.req_('POST', + '/threads/list/' + encodeURIComponent(uid) + '/' + page, + options ?? {}, + ); + } +}