Created
February 7, 2024 05:43
-
-
Save egorvinogradov/5e31ae95a05b166f6c7608c83ea944b1 to your computer and use it in GitHub Desktop.
DomURLAsRequestAdapter (using the Adapter pattern)
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
/** | |
* Use design pattern Adapter to implement DomURLAsRequestAdapter that would adapt DomURL as Request | |
*/ | |
export interface Request { | |
getOrigin(): string | |
getPath(): Array<string> | |
} | |
export class DomURL { | |
public constructor(public readonly path: string) {} | |
} | |
/** | |
* @example | |
* const domURL = new DomURL('https://example.com/my/long/path/'); | |
* const domURLAsRequestAdapter = new DomURLAsRequestAdapter(domURL); | |
* domURLAsRequestAdapter.getOrigin(); // https://example.com | |
* domURLAsRequestAdapter.getPath(); // ['my', 'long', 'path'] | |
*/ | |
export class DomURLAsRequestAdapter implements Request { | |
public domURL: DomURL; | |
public constructor(domURL: DomURL){ | |
this.domURL = domURL; | |
} | |
public getOrigin(): string { | |
const url = new URL(this.domURL.path); | |
return url.origin; | |
} | |
public getPath(): Array<string> { | |
const url = new URL(this.domURL.path); | |
return url.pathname.replace(/^\//, '').replace(/\/$/, '').split('/'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment