From b986900b10547403040068c78d8c666307b84aae Mon Sep 17 00:00:00 2001 From: XuPeiYao Date: Tue, 5 Dec 2017 22:29:44 +0800 Subject: [PATCH] Add relative path parse support and test --- src/test.ts | 16 ++++++++++++++++ src/uriBuilder.ts | 15 ++++++++++++++- src/uriSchemaPortList.ts | 1 + 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/test.ts b/src/test.ts index 955aee1..a58d929 100644 --- a/src/test.ts +++ b/src/test.ts @@ -106,6 +106,15 @@ var uriDataSet = [ pathSegments: ['watch'] } ], + [ + './a/b/c/watch', + { + schema: UriBuilder.relative, + host: '.', + port: undefined, + pathSegments: ['a', 'b', 'c', 'watch'] + } + ], [ 'https://www.youtube.com/watch?v=TlzfSfc_ymI&%E4%B8%AD%E6%96%87=%E4%B8%AD%E6%96%87', { @@ -200,3 +209,10 @@ console.assert( emptyBuilder.toString() === 'http://guest@example/home/index#top' ); console.log(emptyBuilder.toString()); + +hr(); +console.info('Relative Test'); +const relativeBuilder = UriBuilder.parse('./home/exam?id=0'); +relativeBuilder.query.id = 1; +console.assert(relativeBuilder.toString() === './home/exam?id=1'); +console.log(relativeBuilder.toString()); diff --git a/src/uriBuilder.ts b/src/uriBuilder.ts index 060bf6c..095fd7d 100644 --- a/src/uriBuilder.ts +++ b/src/uriBuilder.ts @@ -22,6 +22,7 @@ export interface IUriModel { } export class UriBuilder implements IUriModel { + public static relative = 'relative'; public schema: string; private _authority: IUriAuthority; @@ -63,7 +64,10 @@ export class UriBuilder implements IUriModel { public static parse(uri: string): UriBuilder { if (!this.isUriFormat(uri)) { - throw new Error('URI Format ERROR'); + uri = `${UriBuilder.relative}://${uri}`; + if (!this.isUriFormat(uri)) { + throw new Error('URI Format ERROR'); + } } const result = new UriBuilder(); @@ -126,8 +130,17 @@ export class UriBuilder implements IUriModel { this._authority.password = password; } + public isRelative(): boolean { + return this.schema === UriBuilder.relative; + } + public toString(): string { let result = `${this.schema}://`; + + if (this.schema === UriBuilder.relative) { + result = ''; + } + if (this.authority && this.authority.user) { result += this.authority.user; if (this.authority.password) { diff --git a/src/uriSchemaPortList.ts b/src/uriSchemaPortList.ts index 7ad3350..82e7ccd 100644 --- a/src/uriSchemaPortList.ts +++ b/src/uriSchemaPortList.ts @@ -1,6 +1,7 @@ export class UriSchemaPortList { static http = 80; static https = 80; + static relative = undefined; public static getPort(schema: string): number { return this[schema.toLowerCase()];