Skip to content

Instantly share code, notes, and snippets.

@contribu
Created February 13, 2020 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save contribu/28b675feac45dbe8a7821a520be39033 to your computer and use it in GitHub Desktop.
Save contribu/28b675feac45dbe8a7821a520be39033 to your computer and use it in GitHub Desktop.
// nuxt module
// serialize server side rendering to prevent singleton problem like https://github.com/vuex-orm/vuex-orm/issues/514
let seq = 1
let lockPromise
const auxData = new WeakMap()
const lock = async (data) => {
while (lockPromise) {
console.log('serial-render waiting')
await lockPromise
}
lockPromise = new Promise((resolve) => {
data.lockPromiseResolve = resolve
})
}
const unlock = (data) => {
if (data.lockPromiseResolve) {
lockPromise = void 0
const resolve = data.lockPromiseResolve
data.lockPromiseResolve = void 0
resolve()
}
}
export default function () {
this.nuxt.hook('vue-renderer:ssr:prepareContext', async ({ req }) => {
const data = { id: seq++ }
auxData.set(req, data)
await lock(data)
console.log('serial-render start ' + data.id)
})
this.nuxt.hook('vue-renderer:ssr:context', async ({ req }) => {
const data = auxData.get(req)
console.log('serial-render finished ' + data.id)
unlock(data)
})
this.nuxt.hook('render:errorMiddleware', async (connectInstance) => {
connectInstance.use((err, req, res, next) => {
const data = auxData.get(req)
if (data) {
console.log('serial-render error ' + data.id)
unlock(data)
}
next(err)
})
})
}
@contribu
Copy link
Author

Another solution of vuex-orm/vuex-orm#514

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment