Skip to content

Instantly share code, notes, and snippets.

@egorvinogradov
Created February 7, 2024 05:43
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 egorvinogradov/5e31ae95a05b166f6c7608c83ea944b1 to your computer and use it in GitHub Desktop.
Save egorvinogradov/5e31ae95a05b166f6c7608c83ea944b1 to your computer and use it in GitHub Desktop.
DomURLAsRequestAdapter (using the Adapter pattern)
/**
* 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