svelte/src/index.js

  1. /**
  2. * @module @serveside/svelte
  3. */
  4. /**
  5. * @param req
  6. * @param res
  7. * @param next
  8. */
  9. async function htmlLoader(req, res, next) {
  10. const { ResolvedComponent, componentProps, component } = req.locals;
  11. try {
  12. const { html, css } = ResolvedComponent.render(componentProps);
  13. res.locals.html = `
  14. <style>${css.code}</style>
  15. <div
  16. data-serveside-component="${component}"
  17. data-serveside-id="serveside_${req.id}"
  18. >${html}</div>
  19. <script>
  20. window.__SERVESIDE_LOAD_PROPS__ ||= {};
  21. window.__SERVESIDE_LOAD_PROPS__[${req.id}] = ${JSON.stringify(
  22. componentProps,
  23. null,
  24. 3,
  25. )};
  26. </script>
  27. `;
  28. next();
  29. } catch (error) {
  30. res.locals.error = error;
  31. next('route');
  32. }
  33. }
  34. /**
  35. * @param req
  36. * @param res
  37. * @param next
  38. */
  39. function errorHtmlLoader(req, res, next) {
  40. const { componentProps, component, error } = req.locals;
  41. res.locals.html = `
  42. <div
  43. data-serveside-component="${component}"
  44. data-serveside-id="serveside_${req.id}"
  45. ></div>
  46. <script>
  47. window.__SERVESIDE_LOAD_ERROR__ = ${JSON.stringify(error.message)};
  48. window.__SERVESIDE_LOAD_PROPS__ ||= {};
  49. window.__SERVESIDE_LOAD_PROPS__[${req.id}] = ${JSON.stringify(
  50. componentProps,
  51. null,
  52. 3,
  53. )};
  54. </script>
  55. `;
  56. next();
  57. }
  58. /**
  59. * @param __
  60. * @param res
  61. */
  62. function htmlRenderer(__, res) {
  63. res.send(res.locals.html);
  64. }
  65. export { htmlLoader, errorHtmlLoader, htmlRenderer };