Add Flow Type Alias for function which returns an object (session_mutex)

This commit is contained in:
Jon D
2018-02-27 22:25:30 +00:00
parent 8655ec6baf
commit 48577aeb63

View File

@@ -1,10 +1,19 @@
// @flow
// A per-domain session mutex backed by a cookie and dead man's
// switch. If the session crashes, the mutex will auto-release
// after 5 seconds.
export function utilSessionMutex(name) {
var mutex = {},
intervalID;
// This is a type alias (https://flow.org/en/docs/types/aliases/) which allows flow to understand the object returned by utilSessionMutex in other files.
type utilSessionMutexType = {
lock: () => boolean,
unlock: () => void,
locked: () => boolean
};
// This accepts a string and returns an object that complies with utilSessionMutexType
export function utilSessionMutex(name: string): utilSessionMutexType {
var mutex = {};
var intervalID: ?IntervalID; // This indicates a Maybe type - intervalId can be null so we need to use "?IntervalID", not "IntervalID"
function renew() {
var expires = new Date();
@@ -12,7 +21,7 @@ export function utilSessionMutex(name) {
document.cookie = name + '=1; expires=' + expires.toUTCString();
}
mutex.lock = function() {
mutex.lock = function (): boolean {
if (intervalID) return true;
var cookie = document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + name + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1');
if (cookie) return false;
@@ -21,14 +30,14 @@ export function utilSessionMutex(name) {
return true;
};
mutex.unlock = function() {
mutex.unlock = function (): void {
if (!intervalID) return;
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
clearInterval(intervalID);
intervalID = null;
};
mutex.locked = function() {
mutex.locked = function (): boolean {
return !!intervalID;
};