コード例 #1
0
exports.search = query=> {
    var connection = new Connection();
    return connection.connect()
        .then(connection.collection.bind(connection, Tables.MY_PLACES_2))
        .then(coll=> {
            var regex = new RegExp(query, "gi");
            return Promise.all([
                coll.find({name: regex}, {name: 1, _id: 1}).sort({score: -1}).limit(3).toArray()
                    .then(R.map(place=>Object.assign({seo_url:"/" + SeoUrl.createURL(place.name)},place)))

                , coll.find({category_list: regex}, {category_list: 1}).sort({score: -1}).limit(3).toArray()
                    .then(R.compose(R.map(cat=> {
                        return {
                            seo_url: "/" + SeoUrl.createURL(cat)
                            , name: cat
                            , query: cat
                        }
                    }), R.uniq, R.filter(cat=>cat.match(regex)), R.flatten, R.map(R.prop("category_list"))))

            ])
        })
        .then(([places,categories])=> {
            return {
                body: {
                    places
                    , categories
                }
            }
        })
        .then(R.tap(_=>connection.db.close()))
        .catch(R.tap(_=>connection.db.close()))
};
コード例 #2
0
ファイル: storage.js プロジェクト: amsross/be-ultimatefris
 update: (storeName, game, cb) => {
   storage(store).read(storeName, r.compose(
     r.tap(cb),
     r.tap(games => { store[storeName] = JSON.stringify(games) }),
     r.append(game),
     r.reject(r.propEq('id', game.id))))
 },
コード例 #3
0
function importToMDB() {
    Promise.resolve(JSON.parse(fs.readFileSync("imprese-google-2.json")))
        .then(R.compose(
            R.map(impresa=>impresa.google.results)
            , R.filter(impresa=> {
                return impresa.google.results && impresa.google.results.length > 0
            })))
        .then(R.flatten)
        .then(imprese=> {
            var connection = new Connection();
            return connection.connect()
                .then(db=> {
                    var coll = db.collection(Tables.GOOGLE_PLACES);
                    return Promise.all(imprese.map(impresa=>{
                        return coll.findOneAndUpdate({place_id:impresa.place_id},{$set:impresa},{upsert:true})
                    }))

                        .then(R.tap(_=>connection.db.close()))
                        .catch(R.tap(_=>connection.db.close()))

                })
        })
        .then(R.tap(_=>process.exit(0)))
        .catch(R.tap(_=>process.exit(1)));
}
コード例 #4
0
	test("Monads as programmable commas", function () {

		// map :: (ObjectA -> ObjectB), Monad -> Monad[ObjectB]
		const map = R.curry((f, container) => container.map(f));
		// chain :: (ObjectA -> ObjectB), M -> ObjectB
		const chain = R.curry((f, container) => container.chain(f));

		const lift = R.curry((f, obj) => Maybe.fromNullable(f(obj)));

		const trace = R.curry((msg, obj) => console.log(msg));

		const showStudent = R.compose(
			R.tap(trace('Student printed to the console')),
			map(R.tap(console.log)),   //-> Using R.tap to simulate the side effect (in the book we write to the DOM)

			R.tap(trace('Student info converted to CSV')),
			map(csv),

			map(R.props(['ssn', 'firstname', 'lastname'])),

			R.tap(trace('Record fetched successfully!')),
			chain(findStudent),

			R.tap(trace('Input was valid')),
			chain(checkLengthSsn),
			lift(cleanInput)
		);

		let result = showStudent('444-44-4444').getOrElse('Student not found!');
		expect(result).toEqual('444-44-4444,Alonzo,Church');
	});
コード例 #5
0
                .then(db=> {
                    var coll = db.collection(Tables.GOOGLE_PLACES);
                    return Promise.all(imprese.map(impresa=>{
                        return coll.findOneAndUpdate({place_id:impresa.place_id},{$set:impresa},{upsert:true})
                    }))

                        .then(R.tap(_=>connection.db.close()))
                        .catch(R.tap(_=>connection.db.close()))

                })
コード例 #6
0
 .then(db=> {
     var placesColl = db.collection(Tables.MY_PLACES_2);
     return placesColl.find({category_list: "cinema"}, {_id: 1}).toArray()
         .then(cinemas=> {
             cinemas = cinemas.map(cinema=>cinema._id.toString());
             return cinemas.includes(id);
         })
         .then(R.tap(_=>connection.db.close()))
         .catch(R.tap(_=>connection.db.close()))
 });
コード例 #7
0
ファイル: server.js プロジェクト: bwestergard/reach
 (jsFileMetaData) => pipeP(
   prop('contents_url'),
   getJsonFromHttp,
   tap(ej),
   prop('download_url'),
   tap(ej),
   getBodyFromHttp,
   commentOutEverything,
   (newContents) => ({newContents, jsFileMetaData}) // TODO remove this weird device
 )(jsFileMetaData)
コード例 #8
0
exports.findById = id=> {
    var connection = new Connection();
    return connection.connect()
        .then(connection.collection.bind(connection, Tables.MY_PLACES_2))
        .then(coll=> {
            return coll.findOne({_id: ObjectId(id)});
        })
        .then(R.tap(_=>connection.db.close()))
        .then(mapDetailPlace)
        .catch(R.tap(_=>connection.db.close()))

};
コード例 #9
0
exports.findMyPlaceByFacebookId = id_facebook=> {
    var connection = new Connection();
    return connection.connect()
        .then(connection.collection.bind(connection, Tables.MY_PLACES_2))
        .then(coll=> {
            return coll.findOne({id_facebook});
        })
        .then(R.tap(_=>connection.db.close()))
        .then(mapDetailPlace)
        .catch(R.tap(_=>connection.db.close()))

};
コード例 #10
0
ファイル: invite.js プロジェクト: subvisual/kraken
module.exports = function(user) {
  logger.log('info', 'slack details', user);

  return verifyDependencies()
    .then(function() {
      return new webdriver.Builder().forBrowser('chrome').build();
    })
    .then(R.tap(R.invoke('get', [URI.slack])))
    .then(login)
    .then(R.tap(R.invoke('get', [URI.slackInvites])))
    .then(R.curry(fillUserInformation)(user))
    .then(successMessage)
    .catch(errorMessage);
};
    .then( places =>{
        var connection=new Connection();
        return connection.connect()
            .then(connection.collection.bind(connection,Tables.GOOGLE_PLACES))
            .then(coll=>{
                var promises = places.map(place=> {
                    return coll.findOneAndUpdate({place_id:place.place_id},{$set:place},{upsert:true})
                });
                return Promise.all(promises);
            })
            .then(R.tap(_=>connection.db.close()))
            .catch(R.tap(_=>connection.db.close()))

    })
コード例 #12
0
ファイル: index.js プロジェクト: raine/taim
const taim = (...args) => {
  const color = chalk[nextColor()];
  const [val, label] = getArgs(...args);

  return cond([
    [ hasThenFn, (val) => {
      const start = process.hrtime();
      val.then(() => {
        printDuration(start, color, label);
      });

      return val;
    } ],
    [ isFunctionOrAsyncFunction, (val) =>
      (...args) => {
        const start = process.hrtime();
        const res = val(...args);
        const fn = () => printDuration(start, color, label);

        if (res && hasThenFn(res))
          res.then(fn);
        else
          fn();

        return res;
      }
    ],
    [ T, tap(val => {
      println(process.stderr, `taim error: input should be a async function, function, or thenable, instead got a ${type(val)}`);
    }) ]
  ])(val);
};
コード例 #13
0
     .then(function (exists) {
     log_1.log('found %s ?', exePath, exists);
     if (!exists) {
         throw notInstalledErr("Browser " + name + " file not found at " + exePath);
     }
     // on Windows using "--version" seems to always start the full
     // browser, no matter what one does.
     var args = [
         'datafile',
         'where',
         "name=\"" + doubleEscape(exePath) + "\"",
         'get',
         'Version',
         '/value'
     ];
     return execa('wmic', args)
         .then(function (result) { return result.stdout; })
         .then(ramda_1.trim)
         .then(ramda_1.tap(log_1.log))
         .then(getVersion)
         .then(function (version) {
         log_1.log("browser %s at '%s' version %s", name, exePath, version);
         return {
             name: name,
             version: version,
             path: exePath
         };
     });
 })
コード例 #14
0
ファイル: last-commit-id.js プロジェクト: bahmutov/ggit
/*
 Returns the last commit id
*/
function lastCommitId (options) {
  options = options || {}
  var resultId
  function addBuildInfo (id) {
    resultId = id

    try {
      return utils.addBuildInfo(options, id)
    } catch (e) {
      console.error('Problem adding build information to commit SHA')
      console.error(e.message)
      return utils.defaultBuildInfo(id)
    }
  }

  return findCommit()
    .then(cleanOutput)
    .then(
      R.tap(function (id) {
        console.log('last commit:', id)
        resultId = id
      })
    )
    .then(addBuildInfo)
    .then(function (build) {
      return saveIntoFile(options.file, build)
    })
    .then(function () {
      return resultId
    })
}
コード例 #15
0
ファイル: index.spec.js プロジェクト: pagarme/pagarme-js
test('when Pagarme is offline and encryption key is used', () =>
  pagarme.client.connect({
    encryption_key: 'nwdu91jd9',
    options: {
      baseURL: 'http://a-big-non-existent-website-from-interwebs.nope',
    },
  })
    .then(tap(client => expect(client.authentication.encryption_key).toBe('nwdu91jd9'))))
コード例 #16
0
ファイル: multivarka.js プロジェクト: ZigGreen/webdev-tasks-2
export const multivarka = (...reqBuildChain) => compose(
  tap(startRequest),
  over(lensProp('query'), RWhen(
    pathSatisfies(equals(0), ['$and', 'length']),
    omit(['$and'])
  )),
  ...reqBuildChain
)(RequestType);
コード例 #17
0
		const showStudent = (ssn) =>
			Maybe.fromNullable(ssn)
				.map(cleanInput)
				.chain(checkLengthSsn)
				.chain(findStudent)
				.map(R.props(['ssn', 'firstname', 'lastname']))
				.map(csv)
				.map(R.tap(console.log));  //-> Using R.tap to simulate the side effect (in the book we write to the DOM)
コード例 #18
0
function getFacebookPlacesCollection() {
    var connection = new Connection();
    return connection.connect()
        .then(_=>Tables.FACEBOOK_PLACES)
        .then(connection.collection.bind(connection))
        .then(coll=> {
            return coll.find().toArray()
        })
        .then(R.tap(_=>connection.db.close()))
}
コード例 #19
0
exports.eventi = ({start_time, end_time, limit})=> {
    var connection = new Connection();

    return connection.connect()

        .then(db=> {
            var myPlaces = db.collection(Tables.MY_PLACES_2);
            var myEvents = db.collection(Tables.MY_EVENTS);
            var query = {start_time: {$gte: start_time.getTime()}};
            if (end_time) {
                query.end_time = {$lte: end_time.getTime()};
            }
            return Promise.all([
                myPlaces.find().toArray()
                , myEvents.find(query).limit(limit).sort({start_time:1}).toArray()
            ])
        })
        .then(getEvents())
        .then(R.tap(_=>connection.db.close()))
        .catch(R.tap(_=>connection.db.close()));
};
コード例 #20
0
function checkSensitiveFiles (options) {
  var start
  if (is.array(options)) {
    log('assuming got array of filenames to check for leaked data')
    start = Promise.resolve(options)
  } else {
    start = collectFiles(options)
  }
  return start
    .then(leaveSensitive)
    .then(R.tap(print))
    .then(findLeakedData)
}
コード例 #21
0
exports.findEventById = id=> {
    var connection = new Connection();
    return connection.connect()
        .then(connection.collection.bind(connection, Tables.MY_EVENTS))
        .then(coll=> coll.findOne({_id: ObjectId(id)}))
        .then(event=> {
            var myPlaceColl = connection.db.collection(Tables.MY_PLACES_2);
            var id_owner = event.owner && event.owner.id;
            var id_place = event.place && event.place.id;
            return Promise.all([
                id_owner ? myPlaceColl.findOne({id_facebook: id_owner}) : Promise.resolve(null),
                id_place ? myPlaceColl.findOne({id_facebook: id_place}) : Promise.resolve(null)
            ]).then(([owner,place])=> {
                var description = formatDescription(event.description);
                if (!place && owner) {
                    place = owner;
                } else if (!owner && place) {
                    owner = place;
                } else if (!place && !owner) {
                    place = owner = {};
                }
                place.seo_url = `/${SeoUrl.createURL(place.name)}`;
                owner.seo_url = `/${SeoUrl.createURL(owner.name)}`;

                return Object.assign({
                    image: R.view(R.lensPath(['cover', 'source']), event)
                }, event, {
                    description
                    , raw_description: event.description
                    , owner
                    , place
                })
            });


        })
        .then(R.tap(_=>connection.db.close()))
        .catch(R.tap(_=>connection.db.close()))
};
コード例 #22
0
ファイル: index.spec.js プロジェクト: pagarme/pagarme-js
      .then((company) => {
        const ek = company.encryption_key.test

        return pagarme.client.connect({ encryption_key: ek })
        .then(tap(client => expect(client.authentication.encryption_key)
        .toBe(ek)))
        .then(client => client.transactions.calculateInstallmentsAmount({
          amount: 1,
          interest_rate: 100,
        }))
        .then(result => expect(result).toBeTruthy())
        .catch(err =>
          expect(err.message).not.toBe('You must supply a valid key'))
      })
コード例 #23
0
exports.findByChannel = function (id, options = {limit: 12, filters: []}) {
    var connection = new Connection();

    return connection.connect()
        .then(db=> {
            var my_places = db.collection(Tables.MY_PLACES_2);
            var query = {};
            if (id) {
                var _regexp = new RegExp(id, "gi");
                query = {category_list: {$all: options.filters.concat([_regexp])}};
            }


            return my_places.find(query)
                .sort({score: -1})
                .limit(options.limit)
                .toArray()
                .then(eliminaEccezioni(id))
        })
        .then(R.tap(_=>connection.db.close()))
        .then(R.map(mapDetailPlace))
        .catch(R.tap(_=>connection.db.close()))
};
コード例 #24
0
exports.eventiByPlace = ({start_time, end_time, limit, id_place})=> {
    var connection = new Connection();

    return connection.connect()
    //.then(connection.collection.bind(connection, Tables.MY_EVENTS))
        .then(db=> {
            var myPlaces = db.collection(Tables.MY_PLACES_2);
            var myEvents = db.collection(Tables.MY_EVENTS);
            return myPlaces.findOne({_id: ObjectId(id_place)}).then(my_place=> {
                var time_query = {start_time: {$gte: start_time.getTime()}};
                if (end_time) {
                    time_query.end_time = {$lte: end_time.getTime()};
                }

                return myEvents.find(
                    {
                        $and: [
                            time_query,
                            {
                                $or: [
                                    {"owner.id": {$in: my_place.id_facebook}}
                                    , {"place.id": {$in: my_place.id_facebook}}
                                ]
                            }
                        ]
                    }
                ).limit(limit).sort({start_time:1}).toArray()
                    .then(my_events=> {
                        return [[my_place], my_events]
                    })
            })

        })
        .then(getEvents())
        .then(R.tap(_=>connection.db.close()))
        .catch(R.tap(_=>connection.db.close()));
};
コード例 #25
0
ファイル: index.js プロジェクト: raine/taim
const taimCb = (...args) => {
  const color = chalk[nextColor()];
  const [val, label] = getArgs(...args);

  return cond([
    [ isFunction, (val) =>
      (...args) => {
        const origCb = last(args);
        const start = process.hrtime();
        val(...concat(init(args), [ (...cbArgs) => {
          printDuration(start, color, label);
          origCb(...cbArgs);
        } ]));
      }
    ],
    [ T, tap(val => {
      println(process.stderr, `taim error: input should be a function, instead got a ${type(val)}`);
    }) ]
  ])(val);
};
コード例 #26
0
ファイル: changed-files-after.js プロジェクト: bahmutov/ggit
// returns list of unique changed file after the given commit
function changedFilesAfter (sha, branch) {
  if (!branch) {
    branch = 'master'
  }
  la(is.unemptyString(sha), 'missing from SHA', sha)
  debug('changed files after %s', sha)
  debug('on branch %s', branch)
  return commits
    .after(sha, branch)
    .then(ids)
    .then(
      R.tap(list => {
        debug('commits')
        debug(list)
      })
    )
    .then(stats)
    .then(wait)
    .then(changes)
    .then(justFiles)
}
コード例 #27
0
ファイル: charge.js プロジェクト: andyleggett/website
  chain,
  prop,
  pick,
  propEq,
  reject,
  or,
  tap,
  curry,
  merge,
  identity,
  sortBy,
  head,
  __
} from 'ramda';

const log = tap(console.log.bind(console));
//const error = tap(console.error.bind(console));

const error = (error) => {
  console.log('Error', error);
};

var currentMapMaker;
var currentLocation;

var apiOptions = {
  maxResults: 10,
  distance: 10
};

var geoOptions = {
コード例 #28
0
module.exports = function ($firebaseAuth, firebaseApp, firebaseUrl, empiricalBaseURL, $http, localStorageService) {
  var firebaseTokenUrl = empiricalBaseURL.replace(/\/?$/, '/firebase_tokens') + '?app=' + firebaseApp;
  var authObj, offAuth; // offAuth = handler for disabling

  function fetchToken() {
    return $http.post(firebaseTokenUrl).then(function success (response) {
      return response.data.token;
    }, function error (response) {
      console.log('an error occurred while fetching the firebase token: ', response);
    });
  }

  function storeToken(token) {
    localStorageService.set('token', token);
  }

  function resetToken() {
    console.log('resetting the token');
    storeToken(null);
  }

  function getCached(prop) {
    return localStorageService.get(prop);
  }

  // If a token is not provided, fetch and store it.
  var maybeFetchToken = R.ifElse(R.not, R.pipeP(fetchToken, R.tap(storeToken)), R.identity);

  var handleErrors;

  function firebaseAuthWithToken(token) {
    // authObj.$onAuth()
    return authObj.$authWithCustomToken(token).then(R.identity, handleErrors);
  }

  var fetchAndAuthWithToken = R.pipeP(maybeFetchToken, firebaseAuthWithToken);

  var resetAndFetch = R.pipeP(resetToken, fetchAndAuthWithToken);

  // If token is expired, try to re-fetch and auth again.
  handleErrors = R.cond([R.propEq('code', 'EXPIRED_TOKEN'), resetAndFetch],
                          [R.propEq('code', 'INVALID_TOKEN'), resetAndFetch],
                          [R.T, R.identity]); // Fall through to error handlers further down the promise chain.

  var reAuthIfLoggedOut = R.ifElse(R.not, fetchAndAuthWithToken, R.identity);

  function authenticate() {
    if (offAuth) {
      console.log('disabling auth callback');
      offAuth();
    }
    resetToken();
    var ref = new Firebase(firebaseUrl);
    authObj = $firebaseAuth(ref);
    offAuth = authObj.$onAuth(reAuthIfLoggedOut);
    return fetchAndAuthWithToken(getCached('token'));
  }

  return {
    authenticate: authenticate
  };
};
コード例 #29
0
ファイル: file-status.js プロジェクト: bahmutov/ggit
function fileStatus () {
  return exec(cmd)
    .then(R.tap(log))
    .then(stdoutToGroup)
    .then(R.tap(log))
}
コード例 #30
0
const debug = msg => R.tap(R.partial(log, [msg]));