import { createHash } from "crypto" ; import { isPromise } from "./promiseContainer" ; import Command from "./command" ; import asCallback from "standard-as-callback" ; import { CallbackFunction } from "./types" ; export default class Script { private sha : string ; constructor ( private lua , private numberOfKeys = null , private keyPrefix = "" , private readOnly = false ) { this . sha = createHash ( "sha1" ) . update ( lua ) . digest ( "hex" ) ; } execute ( container , args , options , callback ? ) { if ( typeof this . numberOfKeys === "number" ) { args . unshift ( this . numberOfKeys ) ; } if ( this . keyPrefix ) { options . keyPrefix = this . keyPrefix ; } if ( this . readOnly ) { options . readOnly = true ; } const evalsha = new Command ( "evalsha" , [ this . sha ] . concat ( args ) , options ) ; evalsha . isCustomCommand = true ; const result = container . sendCommand ( evalsha ) ; if ( isPromise ( result ) ) { return asCallback ( result . catch ( ( err ) => { if ( err . toString ( ) . indexOf ( "NOSCRIPT" ) === - 1 ) { throw err ; } return container . sendCommand ( new Command ( "eval" , [ this . lua ] . concat ( args ) , options ) ) ; } ) , callback ) ; } asCallback ( evalsha . promise , callback ) ; return result ; } }