UNPKG

@amag-ch/sap_cap_common_objectstore

Version:

NodeJS library to communicate with an objectstore

94 lines (73 loc) 2.49 kB
const cds = require('@sap/cds') const Client = require('./clients/Client') const Persistance = require('./Persistance') const { ObjectNotFound } = require('./errors') const DEBUG = cds.debug('objectstore') module.exports = class ObjectStoreService extends cds.Service { async init() { const persistance = await Persistance.create(this) // @ts-ignore const client = await Client.create(this.options) /** * Create a file. * * @param {string|ReadableStream|Blob|Buffer} content * @param {{ filename?: string, contentType?: string, ID: string }} options * @returns {Promise<string>} */ this.create = async (content, { filename, contentType, ID }) => { if (ID) await persistance.delete(ID) ID ??= cds.utils.uuid() DEBUG?.(`Create new file ${ID} with original filename ${filename}`) await client.put(ID, content, { contentType }) const { contentLength, modifiedAt } = await client.head(ID) await persistance.create({ ID, filename: filename ?? ID, contentType, contentLength, modifiedAt: modifiedAt.toISOString() }) return ID } /** * Delete file. * * @param {string} ID * @returns {Promise<void>} */ this.delete = async (ID) => { DEBUG?.(`Delete file ${ID}`) return persistance.delete(ID) } /** * Read file. * * @param {string} ID * @returns {Promise<ReadableStream>} */ this.readContent = async (ID) => { DEBUG?.(`Read content of file ${ID}`) if (!await persistance.exists(ID)) throw new ObjectNotFound(`File with ID ${ID} not found`) return client.get(ID) } /** * @param {String} ID */ this.deleteFromStore = async (ID) => { DEBUG?.(`Delete file ${ID} from store`) return client.delete(ID) } /** * @param {String} ID * @param {string|ReadableStream|Blob|Buffer} content */ this.addToStore = async (ID, content) => { return client.put(ID, content) } return super.init() } static testing = require('./testing') }