const { Errors } = require('../../shared') const { NodeDescriptorType } = require('../../enum') const fs = require('fs') const exists = async file => { return new Promise(res => { fs.promises.stat(file).then(() => res(true)).catch(() => res(false)) }) } module.exports = exports = async (message, di) => { console.log('[FLUSH]') const Node = di.models.get('fs:Node') const { descriptor } = message.data() const node_uuid = message.socket.session.file_descriptors?.[descriptor] console.log({node_uuid}) if ( !node_uuid ) { return message.send_response( message.fresh().error(Errors.NodeDoesNotExist) ) } // Check if we have a temporary file which has been written to. // If so, we should "flush" the temporary file to the proper storage. const placeholder = message.socket.session.temp_write_files?.[node_uuid] console.log({placeholder}) if ( !placeholder ) { return message.send_response( message.fresh() ) } let stat; try { stat = await fs.promises.stat(placeholder.path) } catch (e) { return message.send_response( message.fresh() ) } const node = await Node.findOne({ uuid: node_uuid, deleted: false, descriptor_type: NodeDescriptorType.File, }) console.log({node}) if ( !node ) { return message.send_response( message.fresh().error(Errors.NodeDoesNotExist) ) } const existing_file = await node.uploaded_file() console.log({existing_file}) if ( existing_file ) { // This is a new write, so delete the old file await existing_file.delete() delete node.uploaded_file_id } // Store the temporary file const new_file = await di.upload.provider().store({ temp_path: placeholder.path, original_name: node.pied_name, mime_type: 'application/octet-stream', // TODO determine from file extension? }) console.log({new_file}) node.uploaded_file_id = new_file.id node.size = stat.size await node.save() console.log({saved_node: node}) message.send_response( message.fresh() ) console.log('[/FLUSH]') }