const stringRegex = /(.*?)(@(.*))?:(.*)/ class ObjID { public bucket: string public key: string public version?: string constructor(bucket: string, key: string, version?: string) { this.bucket = bucket if(!key){ this.key = "/" }else{ this.key = key } if (version){ this.version = version } this.normalize() } public toString(): string { if (this.version) { return `${this.bucket}@${this.version}:${this.key}` }else{ return `${this.bucket}:${this.key}` } } public normalize(): void{ if (!this.key.startsWith("/")){ this.key = "/" + this.key } } public isDirectory(): boolean { return this.key.endsWith("/") } public toURI(): string { return `/f/${this.bucket}${this.key}` } public toJSON(): string{ // HACK: toJSON is required so that apollo can parse the ObjID back to a string // that can be used in gql query return this.toString() } public rename(name: string): ObjID{ const parts = this.key.split("/") parts[parts.length - (this.isDirectory()?2:1)] = name return new ObjID(this.bucket,parts.join("/")) } /** * Get the parent of the object. If Obj is a file then the containing directory * if Obj is a directory it returns the parent * @returns parent ObjID or null if already at root */ public parent(): ObjID | null { if (this.key == "/") { // Already at root. We dont have a parent return null } if (this.isDirectory()) { const parts = this.key.split("/") const parent = new ObjID(this.bucket, parts.slice(0,-2).join("/") + "/") parent.normalize() return parent } else { const parts = this.key.split("/") const parent = new ObjID(this.bucket, parts.slice(0,-1).join("/") + "/") parent.normalize() return parent } } public static fromString(from: string): ObjID{ const match = stringRegex.exec(from) if (!match){ throw new Error("Failed to parse ObjID") } return new ObjID(match[1],match[4],match[3]) } public static fromURI(uri: string): ObjID{ let uri2 = uri if (!uri2.endsWith("/")){ uri2 += "/" } const parts = uri2.split("/") const bucket = parts[2] const key = parts.slice(3).join("/") return new ObjID(bucket,key) } } export default ObjID