import { parseRedisQuery } from "./common" ; import { BasicRedisTcpOptions as Options } from "../basic_options" ; import { ParseError } from "../../errors" ; import { getScheme , parseUri , Scheme , Uri } from "../../uri" ; import { isNullOrUndefined , parseInteger , } from "../../utility" ; import * as _ from "underscore" ; param rawUri returns throws export const parse = ( rawUri ) : Options => { const protocol = getScheme ( rawUri ) ; if ( protocol !== Scheme . Redis && protocol !== Scheme . RedisSecure ) { throw new ParseError ( `unrecognized scheme "${ protocol }"` ) ; } const parsed = parseUri ( rawUri ) ; if ( isNullOrUndefined ( parsed . authority ) ) { throw new ParseError ( `"${ rawUri }" is missing authority` ) ; } const rawOptions = addOptions ( parsed , { protocol } ) ; return { ... rawOptions , ... parseRedisQuery ( parsed ) , } ; } ; /**
 * Accepted options for TCP URIs.
 */ enum Option { Database = "db" , Hostname = "host" , Password = "password" , Port = "port" } param uri param options returns throws const addOptions = ( uri , options ) : Options => _ . reduce ( _ . values ( Option ) , ( iterating , key ) : Options => { switch ( key ) { case Option . Database : return addDatabase ( uri , iterating ) ; case Option . Hostname : return addHostname ( uri , iterating ) ; case Option . Password : return addPassword ( uri , iterating ) ; case Option . Port : return addPort ( uri , iterating ) ; } } , options ) ; param uri param iterating returns throws const addDatabase = ( uri , iterating ) : Options => { if ( uri . path === "/" ) { return iterating ; } return { ... iterating , db : parseDb ( uri . path ) , } ; } ; param uri param iterating returns const addHostname = ( uri , iterating ) : Options => { const authority = uri . authority ! ; return { ... iterating , host : authority . host , } ; } ; param uri param iterating returns const addPassword = ( uri , iterating ) : Options => { const authority = uri . authority ! ; if ( isNullOrUndefined ( authority . userInfo ) || isNullOrUndefined ( authority . userInfo . pass ) ) { return iterating ; } return { ... iterating , password : authority . userInfo . pass , } ; } ; param uri param iterating returns const addPort = ( uri , iterating ) : Options => { const authority = uri . authority ! ; if ( isNullOrUndefined ( authority . port ) ) { return iterating ; } return { ... iterating , port : authority . port , } ; } ; param maybeDb returns const parseDb = ( maybeDb ) : number => { const DB_INDEX = 1 ; const maybeMatches = /^\/0*(\d+)/ . exec ( maybeDb ) ; if ( isNullOrUndefined ( maybeMatches ) ) { throw new ParseError ( `unable to parse "${ maybeDb }" as db path` ) ; } const matches = maybeMatches ; return parseInteger ( matches [ DB_INDEX ] ) ; } ;