Ejemplo n.º 1
0
  it('fails on invalid additionalProperties', done => {
    const registry = new CoreSchemaRegistry();
    const data = { notNum: 'foo' };

    registry
      .compile({
        properties: {
          num: { type: 'number' },
        },
        additionalProperties: false,
      }).pipe(
        mergeMap(validator => validator(data)),
        map(result => {
          expect(result.success).toBe(false);
          expect(result.errors && result.errors[0].message).toContain(
            'should NOT have additional properties');
        }),
    )
      .toPromise().then(done, done.fail);
  });
Ejemplo n.º 2
0
export function discover(config: PluginsConfig, coreContext: CoreContext) {
  const log = coreContext.logger.get('plugins-discovery');
  log.debug('Discovering plugins...');

  const discoveryResults$ = processPluginSearchPaths$(config.pluginSearchPaths, log).pipe(
    mergeMap(pluginPathOrError => {
      return typeof pluginPathOrError === 'string'
        ? createPlugin$(pluginPathOrError, log, coreContext)
        : [pluginPathOrError];
    }),
    shareReplay()
  );

  return {
    plugin$: discoveryResults$.pipe(filter((entry): entry is Plugin => entry instanceof Plugin)),
    error$: discoveryResults$.pipe(
      filter((entry): entry is PluginDiscoveryError => !(entry instanceof Plugin))
    ),
  };
}
function inicializarBase() {

    const leerBDD$ = rxjs.from(leerBDD());

    return leerBDD$
        .pipe(
            mergeMap(
                (respuestaLeerBDD: RespuestaBDD) => {
                    if (respuestaLeerBDD.bdd) {
                        // truty / {}
                        return rxjs.of(respuestaLeerBDD)
                    } else {
                        // falsy / null
                        return rxjs.from(crearBDD())
                    }
                }
            )
        )
        ;
}
function preguntarPorIDUsuario(respuestaBDD: RespuestaBDD) {
    return rxjs
        .from(inquirer.prompt(preguntaBuscarUsuario)) //*********************
        .pipe(
            mergeMap( // respuesta del anterior observable
                (respuesta: BuscarUsuarioPorId) => {

                    const idDelUsuario = respuestaBDD.bdd
                        .usuarios
                        .findIndex( // -1
                            (usuario: Usuario) => {
                                console.log(usuario);
                                return usuario.id === respuesta.idUsuario
                            }
                        );
                    if (idDelUsuario === '-1') {
                        console.log('El id no existe, Intente nuevamente \n');
                        return preguntarPorIDUsuario(respuestaBDD);
                    } else {
                        respuestaBDD.idUsuario = idDelUsuario;
                        return rxjs
                            .from(inquirer.prompt(preguntaBuscarNombreUsuario))//***********************
                            .pipe(
                                map(
                                    (nombre:{nombre:string})=>{
                                        respuestaBDD.usuario ={
                                            id:null,
                                            nombre:nombre.nombre,
                                            tipoCuenta:null,
                                            saldo:null,
                                            password:null
                                        };
                                        return respuestaBDD;
                                    }
                                )
                            );
                    }
                }
            )
        );
}
Ejemplo n.º 5
0
  forkJoin2() {
    const myPromise = val =>
      new Promise(resolve =>
        setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000)
      );

    const source = of([1, 2, 3, 4, 5]);
    // emit array of all 5 results
    const example = source.pipe(mergeMap(q => forkJoin(...q.map(myPromise))));
    /*
      output:
      [
       "Promise Resolved: 1",
       "Promise Resolved: 2",
       "Promise Resolved: 3",
       "Promise Resolved: 4",
       "Promise Resolved: 5"
      ]
    */
    const subscribe = example.subscribe(val => console.log(val));
  }
Ejemplo n.º 6
0
export const loadStateEpic: Epic<any, any> = action$ =>
    action$.ofType(CoreActionTypes.LOAD_STATE)
        .pipe(
            mergeMap((action: typeof loadState) => {
                const theme = localStorage.getItem('theme') || 'solarized dark'
                const actions: IAction[] = [initSettings({
                    theme
                })]

                let servers: any = localStorage.getItem('servers')
                if (servers) {
                    servers = JSON.parse(servers)
                    actions.push(initServers(servers))
                }

                return from([
                    ...actions,
                    loadStateFinished()
                ])
            })
        )
Ejemplo n.º 7
0
    function main(_sources: any) {
      const test$ = of(null).pipe(
        delay(1000),
        mergeMap(() =>
          _sources.HTTP.select('cat').pipe(
            mergeAll(),
            map((res: any) => 'I should not show this, ' + res.text)
          )
        )
      );

      const request$ = of({
        category: 'cat',
        url: uri + '/hello',
      });

      return {
        HTTP: request$,
        Test: test$,
      };
    }
Ejemplo n.º 8
0
/**
 * Perform cleaning of the buffer according to the values set by the user
 * at each clock tick and each times the maxBufferBehind/maxBufferAhead values
 * change.
 *
 * @param {Object} opt
 * @returns {Observable}
 */
export default function BufferGarbageCollector({
  queuedSourceBuffer,
  clock$,
  maxBufferBehind$,
  maxBufferAhead$,
} : {
  queuedSourceBuffer : QueuedSourceBuffer<unknown>;
  clock$ : Observable<number>;
  maxBufferBehind$ : Observable<number>;
  maxBufferAhead$ : Observable<number>;
}) : Observable<never> {
  return observableCombineLatest(clock$, maxBufferBehind$, maxBufferAhead$).pipe(
    mergeMap(([currentTime, maxBufferBehind, maxBufferAhead]) => {
      return clearBuffer(
        queuedSourceBuffer,
        currentTime,
        maxBufferBehind,
        maxBufferAhead
      );
    }));
}
Ejemplo n.º 9
0
 mergeMap_flatMap3() {
   /*
     you can also supply a second argument which receives the source value and emitted
     value of inner observable or promise
   */
   // emit 'Hello'
   const source = of('Hello');
   // mergeMap also emits result of promise
   const myPromise = val =>
     new Promise(resolve => resolve(`${val} World From Promise!`));
   const example = source.pipe(
     mergeMap(
       val => myPromise(val),
       (valueFromSource, valueFromPromise) => {
         return `Source: ${valueFromSource}, Promise: ${valueFromPromise}`;
       }
     )
   );
   // output: "Source: Hello, Promise: Hello World From Promise!"
   const subscribe = example.subscribe(val => console.log(val));
 }
Ejemplo n.º 10
0
/**
 * Iterates over every plugin search path and returns a merged stream of all
 * sub-directories. If directory cannot be read or it's impossible to get stat
 * for any of the nested entries then error is added into the stream instead.
 * @param pluginDirs List of the top-level directories to process.
 * @param log Plugin discovery logger instance.
 */
function processPluginSearchPaths$(pluginDirs: ReadonlyArray<string>, log: Logger) {
  return from(pluginDirs).pipe(
    mergeMap(dir => {
      log.debug(`Scanning "${dir}" for plugin sub-directories...`);

      return fsReadDir$(dir).pipe(
        mergeMap((subDirs: string[]) => subDirs.map(subDir => resolve(dir, subDir))),
        mergeMap(path =>
          fsStat$(path).pipe(
            // Filter out non-directory entries from target directories, it's expected that
            // these directories may contain files (e.g. `README.md` or `package.json`).
            // We shouldn't silently ignore the entries we couldn't get stat for though.
            mergeMap(pathStat => (pathStat.isDirectory() ? [path] : [])),
            catchError(err => [PluginDiscoveryError.invalidPluginPath(path, err)])
          )
        ),
        catchError(err => [PluginDiscoveryError.invalidSearchPath(dir, err)])
      );
    })
  );
}