Created
May 29, 2021 03:27
-
-
Save Ethan-Arrowood/01c998aeea746d01e2bf6aba62fe7237 to your computer and use it in GitHub Desktop.
A simplified state-machine like connection class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ConnectionContext = { | |
state: 'disconnected' | |
methods: { | |
connect: () => Promise<void> | |
} | |
} | { | |
state: 'connected', | |
data: { | |
endpoint: string | |
}, | |
methods: { | |
disconnect: () => Promise<void>, | |
login: () => Promise<void> | |
} | |
} | { | |
state: 'authenticated', | |
data: { | |
endpoint: string, | |
user: string | |
}, | |
methods: { | |
disconnect: () => Promise<void>, | |
logout: () => Promise<void> | |
} | |
} | |
class Connection { | |
private _context: ConnectionContext | |
constructor () { | |
this._context = { | |
state: 'disconnected', | |
methods: { | |
connect: () => this.connect() | |
} | |
} | |
} | |
get context (): ConnectionContext { | |
return this._context | |
} | |
private connect () { | |
this._context = { | |
state: 'connected', | |
methods: { | |
disconnect: () => this.disconnect(), | |
login: () => this.login() | |
}, | |
data: { | |
endpoint: 'http://abcde' | |
} | |
} | |
return Promise.resolve() | |
} | |
private disconnect () { | |
this._context = { | |
state: 'disconnected', | |
methods: { | |
connect: () => this.connect() | |
} | |
} | |
return Promise.resolve() | |
} | |
private login () { | |
this._context = { | |
state: 'authenticated', | |
methods: { | |
disconnect: () => this.disconnect(), | |
logout: () => this.logout() | |
}, | |
data: { | |
endpoint: 'http://abcde', | |
user: 'robot' | |
} | |
} | |
return Promise.resolve() | |
} | |
private logout () { | |
this._context = { | |
state: 'connected', | |
methods: { | |
disconnect: () => this.disconnect(), | |
login: () => this.login() | |
}, | |
data: { | |
endpoint: 'http://abcde' | |
} | |
} | |
return Promise.resolve() | |
} | |
} | |
async function example () { | |
const connection = new Connection() | |
console.log(connection.context.state) | |
if (connection.context.state === 'disconnected') { | |
await connection.context.methods.connect() | |
} | |
console.log(connection.context.state) | |
if (connection.context.state === 'connected') { | |
await connection.context.methods.login() | |
} | |
console.log(connection.context.state) | |
if (connection.context.state === 'authenticated') { | |
await connection.context.methods.logout() | |
} | |
console.log(connection.context.state) | |
if (connection.context.state === 'connected') { | |
await connection.context.methods.disconnect() | |
} | |
console.log(connection.context.state) | |
} | |
example() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment