fastify / point-of-view

Template rendering plugin for Fastify
MIT License
338 stars 86 forks source link

catch async errors #347

Closed cberescu closed 1 year ago

cberescu commented 1 year ago

This will fix https://github.com/fastify/point-of-view/issues/346

Checklist

Uzlopak commented 1 year ago

can we make it a little bit prettier? :)

  function viewEta (page, data, opts) {
    if (opts && opts.layout) {
      try {
        layoutIsValid(opts.layout)
        const that = this
        return withLayout(viewEta, opts.layout).call(that, page, data)
      } catch (error) {
        this.send(error)
        return
      }
    }

    if (!page) {
      this.send(new Error('Missing page'))
      return
    }

    lru.define = lru.set
    engine.configure({
      templates: globalOptions.templates ? globalOptions.templates : lru
    })

    const config = Object.assign({
      cache: prod,
      views: templatesDir
    }, globalOptions)

    const sendContent = html => {
      if (
        config.useHtmlMinifier &&
        typeof config.useHtmlMinifier.minify === 'function' &&
        !isPathExcludedMinification(getRequestedPath(this), config.pathsToExcludeHtmlMinifier)
      ) {
        html = config.useHtmlMinifier.minify(
          html,
          config.htmlMinifierOptions || {}
        )
      }
      this.header('Content-Type', 'text/html; charset=' + charset)
      this.send(html)
    }

    data = Object.assign({}, defaultCtx, this.locals, data)
    // Append view extension (Eta will append '.eta' by default,
    // but this also allows custom extensions)
    page = getPage(page, 'eta')
    if (opts?.async ?? globalOptions.async) {
      engine
        .renderFile(page, data, config)
        .then(sendContent)
        .catch(err => this.send(err))
    } else {
      engine.renderFile(page, data, config, (err, html) => {
        err
          ? this.send(err)
          : sendContent(html)
      })
    }
  }
cberescu commented 1 year ago

@Uzlopak pushed the code as you proposed.