web_lib

Common web application libraries
git clone https://radroots.dev/git/web_lib.git
Log | Files | Refs | LICENSE

web.ts (1625B)


      1 import { err_msg, handle_err, type ResolveError } from "@radroots/utils";
      2 import { cl_fs_error } from "./error.js";
      3 import type { IClientFs, IClientFsFileInfo, IClientFsOpenResult, IClientFsReadBinResolve } from "./types.js";
      4 
      5 export interface IWebFs extends IClientFs {}
      6 
      7 export class WebFs implements IWebFs {
      8     public async exists(path: string): Promise<ResolveError<boolean>> {
      9         try {
     10             const res = await fetch(path, { method: 'HEAD' });
     11             return res.ok;
     12         } catch (e) {
     13             return handle_err(e);
     14         }
     15     }
     16 
     17     public async open(path: string): Promise<ResolveError<IClientFsOpenResult>> {
     18         return { path };
     19     }
     20 
     21     public async info(path: string): Promise<ResolveError<IClientFsFileInfo>> {
     22         try {
     23             const res = await fetch(path, { method: 'HEAD' });
     24             if (!res.ok) return err_msg(res.status === 404 ? cl_fs_error.not_found : cl_fs_error.request_failure);
     25             const size_header = res.headers.get('Content-Length');
     26             const size = size_header ? Number(size_header) : 0;
     27             return { size, isFile: true, isDirectory: false };
     28         } catch (e) {
     29             return handle_err(e);
     30         }
     31     }
     32 
     33     public async read_bin(path: string): Promise<IClientFsReadBinResolve> {
     34         try {
     35             const res = await fetch(path);
     36             if (!res.ok) return err_msg(res.status === 404 ? cl_fs_error.not_found : cl_fs_error.request_failure);
     37             const buf = await res.arrayBuffer();
     38             return new Uint8Array(buf);
     39         } catch (e) {
     40             return handle_err(e);
     41         }
     42     }
     43 }