Created
May 19, 2022 08:06
-
-
Save qutek/224aae26c676f440218731757d09e9c4 to your computer and use it in GitHub Desktop.
[Medusa Local File Service] Custom service to upload files / image directly to server #medusajs #nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/api/index.js | |
import express from 'express'; | |
const uploadDir = 'static'; | |
export default () => { | |
const router = express.Router(); | |
router.use(`/${uploadDir}`, express.static(uploadDir)); | |
return router; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/services/localFile.js | |
import { FileService } from 'medusa-interfaces'; | |
import fs from 'fs'; | |
// static config | |
const baseUrl = 'http://localhost:9000'; | |
const uploadDir = 'static'; | |
class LocalFileService extends FileService { | |
constructor({}, config) { | |
super(); | |
if (!fs.existsSync(uploadDir)) { | |
fs.mkdirSync(uploadDir); | |
} | |
} | |
upload(file) { | |
console.log('UPLOAD FILE', file) | |
return new Promise((resolve, reject) => { | |
fs.copyFile(file.path, `${uploadDir}/${file.originalname}`, (err) => { | |
if (err) throw err; | |
resolve({ | |
url: `${baseUrl}/${uploadDir}/${file.originalname}`, | |
}); | |
}); | |
}); | |
} | |
delete(file) { | |
console.log('DELETE FILE', file); | |
return Promise.resolve('deleted'); | |
} | |
} | |
export default LocalFileService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment