UNPKG

@platform/cell.client

Version:

A strongly typed HTTP client for operating with a CellOS service end-point.

90 lines (89 loc) 3.54 kB
import { ERROR, Schema, util } from '../common'; export class HttpClientCellFile { constructor(args) { this.args = args; } static create(args) { return new HttpClientCellFile(args); } name(path) { const http = this.args.http; const self = this; const parent = this.args.parent; return { async info() { const linkRes = await self.getCellLinkByFilename(path); if (linkRes.error) { return linkRes.error; } if (!linkRes.link) { throw new Error(`Link should exist.`); } const link = linkRes.link; const url = self.args.urls.file(link.uri).info; const res = await http.get(url.toString()); return util.fromHttpResponse(res).toClientResponse(); }, async download(options = {}) { const { expires } = options; const linkRes = await self.getCellLinkByFilename(path); if (linkRes.error) { return linkRes.error; } if (!linkRes.link) { throw new Error(`Link should exist.`); } const { link } = linkRes; const hash = link.query.hash || undefined; const url = parent.url.file .byFileUri(link.uri.toString(), link.ext) .query({ hash, expires }) .toString(); const res = await http.get(url); if (res.ok) { const mime = (res.headers['content-type'] || '').toString().trim(); const bodyType = mime.startsWith('text/') ? 'TEXT' : 'BINARY'; return util.fromHttpResponse(res).toClientResponse({ bodyType }); } else { const message = `Failed while downloading file "${parent.uri.toString()}".`; const httpError = res.contentType.is.json ? res.json : undefined; if (httpError) { const error = `${message} ${httpError.message}`; return util.toError(res.status, httpError.type, error); } else { return util.toError(res.status, ERROR.HTTP.SERVER, message); } } }, }; } async getCellInfo() { const parent = this.args.parent; const res = await parent.info(); if (!res.body) { const message = `Info about the cell "${parent.uri.toString()}" not found.`; const error = util.toError(404, ERROR.HTTP.NOT_FOUND, message); return { res, error }; } else { const data = res.body.data; return { res, data }; } } async getCellLinkByFilename(path) { const parent = this.args.parent; const { error, data } = await this.getCellInfo(); if (!data || error) { return { error }; } const link = Schema.file.links.find(data.links).byName(path); if (!link) { const message = `A link within "${parent.uri.toString()}" to the filename '${path}' does not exist.`; const error = util.toError(404, ERROR.HTTP.NOT_LINKED, message); return { error }; } return { link }; } }