@ -1,6 +1,7 @@
const { promises : fs } = require ( 'fs' ) ;
const path = require ( 'path' ) ;
const Koa = require ( 'koa' ) ;
const { isObject , mapValues } = require ( 'lodash' ) ;
const CURRENT _STATE _KEY = '__CURRENT__' ;
const DEFAULT _STATE _KEY = '__DEFAULT__' ;
@ -8,6 +9,50 @@ const DEFAULT_STATE_KEY = '__DEFAULT__';
const FIXTURE _SERVER _HOST = 'localhost' ;
const FIXTURE _SERVER _PORT = 12345 ;
const fixtureSubstitutionPrefix = '__FIXTURE_SUBSTITUTION__' ;
const fixtureSubstitutionCommands = {
currentDateInMilliseconds : 'currentDateInMilliseconds' ,
} ;
/ * *
* Perform substitutions on a single piece of state .
*
* @ param { unknown } partialState - The piece of state to perform substitutions on .
* @ returns { unknown } The partial state with substititions performed .
* /
function performSubstitution ( partialState ) {
if ( Array . isArray ( partialState ) ) {
return partialState . map ( performSubstitution ) ;
} else if ( isObject ( partialState ) ) {
return mapValues ( partialState , performSubstitution ) ;
} else if (
typeof partialState === 'string' &&
partialState . startsWith ( fixtureSubstitutionPrefix )
) {
const substitutionCommand = partialState . substring (
fixtureSubstitutionPrefix . length ,
) ;
if (
substitutionCommand ===
fixtureSubstitutionCommands . currentDateInMilliseconds
) {
return new Date ( ) . getTime ( ) ;
}
throw new Error ( ` Unknown substitution command: ${ substitutionCommand } ` ) ;
}
return partialState ;
}
/ * *
* Substitute values in the state fixture .
*
* @ param { object } rawState - The state fixture .
* @ returns { object } The state fixture with substitutions performed .
* /
function performStateSubstitutions ( rawState ) {
return mapValues ( rawState , performSubstitution ) ;
}
class FixtureServer {
constructor ( ) {
this . _app = new Koa ( ) ;
@ -57,7 +102,8 @@ class FixtureServer {
state = this . _initialStateCache . get ( statePath ) ;
} else {
const data = await fs . readFile ( statePath ) ;
state = JSON . parse ( data . toString ( 'utf-8' ) ) ;
const rawState = JSON . parse ( data . toString ( 'utf-8' ) ) ;
state = performStateSubstitutions ( rawState ) ;
this . _initialStateCache . set ( statePath , state ) ;
}