* Commits session changes. No more mutations will be allowed after commit. * * @example * await session.commit() // Save all changes to the session store
()
| 711 | * await session.commit() // Save all changes to the session store |
| 712 | */ |
| 713 | async commit() { |
| 714 | if (!this.#valuesStore || this.readonly) { |
| 715 | return |
| 716 | } |
| 717 | |
| 718 | /** |
| 719 | * If the flash messages store is not empty, we should put |
| 720 | * its messages inside main session store. |
| 721 | */ |
| 722 | if (!this.responseFlashMessages.isEmpty) { |
| 723 | const { input, reflashed, ...others } = this.responseFlashMessages.all() |
| 724 | this.put(this.flashKey, { ...reflashed, ...input, ...others }) |
| 725 | } |
| 726 | |
| 727 | debug('committing session data') |
| 728 | |
| 729 | /** |
| 730 | * Touch the session id cookie to stay alive. With "refreshCookie" |
| 731 | * disabled, only send it when the browser does not have this id. |
| 732 | */ |
| 733 | if (this.config.refreshCookie !== false || this.#sessionId !== this.#sessionIdFromCookie) { |
| 734 | this.#ctx.response.cookie(this.config.cookieName, this.#sessionId, this.config.cookie!) |
| 735 | } |
| 736 | |
| 737 | /** |
| 738 | * Delete the session data when the session store |
| 739 | * is empty. |
| 740 | * |
| 741 | * Also we only destroy the session id we read from the cookie. |
| 742 | * If there was no session id in the cookie, there won't be |
| 743 | * any data inside the store either. |
| 744 | */ |
| 745 | if (this.isEmpty) { |
| 746 | if (this.#sessionIdFromCookie) { |
| 747 | await this.#store.destroy(this.#sessionIdFromCookie) |
| 748 | } |
| 749 | this.#emitter.emit('session:committed', { session: this }) |
| 750 | return |
| 751 | } |
| 752 | |
| 753 | /** |
| 754 | * Touch the store expiry when the session store was |
| 755 | * not modified. |
| 756 | */ |
| 757 | if (!this.hasBeenModified) { |
| 758 | if (this.#sessionIdFromCookie && this.#sessionIdFromCookie !== this.#sessionId) { |
| 759 | await this.#store.destroy(this.#sessionIdFromCookie) |
| 760 | await this.#store.write(this.#sessionId, this.#valuesStore.toJSON()) |
| 761 | this.#emitter.emit('session:migrated', { |
| 762 | fromSessionId: this.#sessionIdFromCookie, |
| 763 | toSessionId: this.sessionId, |
| 764 | session: this, |
| 765 | }) |
| 766 | } else { |
| 767 | await this.#store.touch(this.#sessionId) |
| 768 | } |
| 769 | this.#emitter.emit('session:committed', { session: this }) |
| 770 | return |