index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const path = require('path')
  2. const launch = require('launch-editor')
  3. module.exports = (specifiedEditor, srcRoot, onErrorCallback) => {
  4. if (typeof specifiedEditor === 'function') {
  5. onErrorCallback = specifiedEditor
  6. specifiedEditor = undefined
  7. }
  8. if (typeof srcRoot === 'function') {
  9. onErrorCallback = srcRoot
  10. srcRoot = undefined
  11. }
  12. srcRoot = srcRoot || process.cwd()
  13. return function launchEditorMiddleware(req, res) {
  14. let url
  15. try {
  16. const fullUrl = req.url.startsWith('http') ? req.url : `http://localhost${req.url}`
  17. url = new URL(fullUrl)
  18. // eslint-disable-next-line no-unused-vars
  19. } catch (_err) {
  20. res.statusCode = 500
  21. res.end(`launch-editor-middleware: invalid URL.`)
  22. return
  23. }
  24. const file = url.searchParams.get('file')
  25. if (!file) {
  26. res.statusCode = 500
  27. res.end(
  28. `launch-editor-middleware: required query param "file" is missing.`
  29. )
  30. } else {
  31. const resolved = file.startsWith('file://') ? file : path.resolve(srcRoot, file)
  32. launch(resolved, specifiedEditor, onErrorCallback)
  33. res.end()
  34. }
  35. }
  36. }