refactor(pubky): simplify session management using 'fetch-cookie' dependency

This commit is contained in:
nazeh
2024-09-22 18:29:58 +03:00
parent 6544a82d4c
commit 966ccc11e1
7 changed files with 11 additions and 45 deletions

View File

@@ -1,4 +1,3 @@
index.cjs
browser.js
coverage
node_modules

6
pubky/pkg/index.cjs Normal file
View File

@@ -0,0 +1,6 @@
const makeFetchCookie = require("fetch-cookie").default;
let originalFetch = globalThis.fetch;
globalThis.fetch = makeFetchCookie(originalFetch);
module.exports = require('./nodejs/pubky')

View File

@@ -37,5 +37,8 @@
"esmify": "^2.1.1",
"tape": "^5.8.1",
"tape-run": "^11.0.0"
},
"dependencies": {
"fetch-cookie": "^3.0.1"
}
}

View File

@@ -55,12 +55,3 @@ const bytes = __toBinary(${JSON.stringify(await readFile(path.join(__dirname, `.
);
await writeFile(path.join(__dirname, `../../pkg/browser.js`), patched + "\nglobalThis['pubky'] = imports");
// Move outside of nodejs
await Promise.all([".js", ".d.ts", "_bg.wasm"].map(suffix =>
rename(
path.join(__dirname, `../../pkg/nodejs/${name}${suffix}`),
path.join(__dirname, `../../pkg/${suffix === '.js' ? "index.cjs" : (name + suffix)}`),
))
)

View File

@@ -1,6 +1,6 @@
use pkarr::SignedPacket;
use pubky_common::crypto::PublicKey;
use reqwest::{RequestBuilder, Response};
use reqwest::RequestBuilder;
use url::Url;
use crate::error::Result;
@@ -28,7 +28,4 @@ impl PubkyClient {
pub(crate) fn inner_request(&self, method: reqwest::Method, url: Url) -> RequestBuilder {
self.http.request(method, url)
}
pub(crate) fn store_session(&self, _: &Response) {}
pub(crate) fn remove_session(&self, _: &PublicKey) {}
}

View File

@@ -43,8 +43,6 @@ impl PubkyClient {
.send()
.await?;
self.store_session(&response);
self.publish_pubky_homeserver(keypair, &homeserver).await?;
let bytes = response.bytes().await?;
@@ -84,8 +82,6 @@ impl PubkyClient {
self.inner_request(Method::DELETE, url).send().await?;
self.remove_session(pubky);
Ok(())
}
@@ -175,8 +171,6 @@ impl PubkyClient {
.send()
.await?;
self.store_session(&response);
let bytes = response.bytes().await?;
Ok(Session::deserialize(&bytes)?)

View File

@@ -1,6 +1,6 @@
use crate::PubkyClient;
use reqwest::{Method, RequestBuilder, Response};
use reqwest::{Method, RequestBuilder};
use url::Url;
impl PubkyClient {
@@ -13,28 +13,4 @@ impl PubkyClient {
request
}
// Support cookies for nodejs
pub(crate) fn store_session(&self, response: &Response) {
if let Some(cookie) = response
.headers()
.get("set-cookie")
.and_then(|h| h.to_str().ok())
.and_then(|s| s.split(';').next())
{
self.session_cookies
.write()
.unwrap()
.insert(cookie.to_string());
}
}
pub(crate) fn remove_session(&self, pubky: &pkarr::PublicKey) {
let key = pubky.to_string();
self.session_cookies
.write()
.unwrap()
.retain(|cookie| !cookie.starts_with(&key));
}
}