API 1
This commit is contained in:
parent
1d4efd738c
commit
cb0d25030d
2 changed files with 38 additions and 10 deletions
|
@ -43,6 +43,16 @@ export const registerStreamProtocol = () => {
|
|||
// Convert e.g. "%20" to spaces.
|
||||
const path = decodeURIComponent(pathname);
|
||||
switch (host) {
|
||||
case "read":
|
||||
try {
|
||||
return net.fetch(pathToFileURL(path).toString());
|
||||
} catch (e) {
|
||||
log.error(`Failed to read stream for ${url}`, e);
|
||||
return new Response(`Failed to read stream: ${e.message}`, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
|
||||
case "write":
|
||||
try {
|
||||
await writeStream(path, request.body);
|
||||
|
@ -55,16 +65,6 @@ export const registerStreamProtocol = () => {
|
|||
);
|
||||
}
|
||||
|
||||
case "read":
|
||||
try {
|
||||
return net.fetch(pathToFileURL(path).toString());
|
||||
} catch (e) {
|
||||
log.error(`Failed to read stream for ${url}`, e);
|
||||
return new Response(`Failed to read stream: ${e.message}`, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
|
||||
default:
|
||||
return new Response("", { status: 404 });
|
||||
}
|
||||
|
|
|
@ -4,6 +4,34 @@
|
|||
* NOTE: These functions only work when we're running in our desktop app.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Stream the given file from the user's local filesystem.
|
||||
*
|
||||
* **This only works when we're running in our desktop app**. It uses the
|
||||
* "stream://" protocol handler exposed by our custom code in the Node.js layer.
|
||||
* See: [Note: IPC streams].
|
||||
*
|
||||
* @param path The path on the file on the user's local filesystem whose
|
||||
* contents we want to stream.
|
||||
*
|
||||
* @return A standard web {@link Response} object that contains the contents of
|
||||
* the file. In particular, `response.body` will be a {@link ReadableStream}
|
||||
* that can be used to read the files contents in a streaming, chunked, manner.
|
||||
*/
|
||||
export const readStream = async (path: string) => {
|
||||
const req = new Request(`stream://read${path}`, {
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
const res = await fetch(req);
|
||||
if (!res.ok)
|
||||
throw new Error(
|
||||
`Failed to read stream from ${path}: HTTP ${res.status}`,
|
||||
);
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Write the given stream to a file on the local machine.
|
||||
*
|
||||
|
|
Loading…
Reference in a new issue