npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cf-services

v2.0.1

Published

Simple node package to lookup bound services in Cloud Foundry

Downloads

77

Readme

npm Build Status

cf-services

Simple node package to look up bound services in Cloud Foundry

The change log describes the changes between versions.

Background

Cloud Foundry provides an application with the credentials of bound service instances via environment variable VCAP_SERVICES.

VCAP_SERVICES

Notice that VCAP_SERVICES object uses service names as keys. Since multiple instances of the same service can be bound to one application, the property values are arrays of service bindings. This makes it inconvenient for applications to look up required service bindings in a reliable way.

See this presentation for more details.

Install

npm install --save cf-services

Usage

If you bind a service to your app like this:

cf create-service redis small my-redis
cf bind-service my-app my-redis

You can get this binding in your app like this:

var cfServices = require('cf-services');

var redis = cfServices('my-redis');
// redis = { label: '...', name: 'my-redis', credentials: {...}, ... }

Unfortunately the instance name is rarely known in advance, so you may pass it as a separate environment variable:

cf set-env my-app REDIS_SERVICE_NAME my-redis

Then grab it in your app like this:

var redis = cfServices(process.env.REDIS_SERVICE_NAME);

You can also look up a service binding with matching properties:

var redis = cfServices({ label: 'redis', plan: 'large' });

or get the binding with a certain tag:

var store = cfServices({ tags: ['store'] }); 

or use a custom function to filter the bindings:

var redis = cfServices(binding => 
  binding.label === 'redis' || binding.tags.includes('redis')); 

Finally, if called without arguments, it will return a flat object of all service bindings keyed by their names:

var bindings = cfServices();
// bindings = { 'my-redis1': {...}, 'my-redis2': {...}, ... }

Notice that this is different from VCAP_SERVICES which uses service names (label property) as keys.

Note that cfServices will throw an exception if no service binding matches the given criteria or multiple service bindings match the criteria. This way you don't need to perform additional checks in your code. You know that if the call succeeds, there is exactly one match.

In case of inconsistent configuration, an application should abort during startup with a clear error message instead of keep running and fail later during productive use. Even worse, the application might seem to work without errors but produce wrong results which are hard to revert. For example an application writing to a wrong database.

In some cases you don't want to deal with exceptions. Then you can filter service bindings and deal with varying number of matches:

var matches = cfServices.filter({ tags: ['redis'] }); 
if (matches === 1) {
  let redis = matches[0];
} else {
  // handle misconfiguration
}

Local execution

The ability to test your application locally outside Cloud Foundry is important as it improves turnaround time and hence developer productivity.

One option is to use a tool like dotenv that mocks the process environment. The problem with solutions like this is that they pollute your productive code with code that is used only during testing.

A better approach is to setup the process environment (VCAP_SERVICES) in a similar way to Cloud Foundry. Then it is completely transparent to your app if it is running locally or in Cloud Foundry. You can do this in a shell script or using some tool like fireup which supports multiline environment variables.

API

cfServices([query, [description]])

  • query
    • if query argument is not provided, returns a flat object of service bindings using instance names as keys
    • if query is a string, returns the binding with the same instance name
    • if query is an object, returns the service binding with matching properties, see _.filter.
    • if query is a function, it should take a service binding as argument and return a boolean. cfServices then returns the service binding for which the query function returns true.
  • description - optional query description used in error messages
  • returns the service binding matching the query or an object with all service bindings if query is not provided
  • throws an error if:
    • VCAP_SERVICES is not defined
    • VCAP_SERVICES value is not a valid JSON string
    • No service binding matches the query
    • Multiple service bindings match the query

Parses VCAP_SERVICES environment variable and returns the matching service binding.

For example these two are equivalent except that (1) will throw if there is no service instance with name some-instance while (2) will return undefined.

cfServices('some-name')   // (1)
cfServices()['some-name'] // (2)

cfServices.filter(query)

  • query - object or filter function
  • returns an array of matching service bindings, empty if there are no matches
  • throws an error if:
    • VCAP_SERVICES is not defined
    • VCAP_SERVICES value is not a valid JSON string

Unlike cfServices, this function will not throw an error if there are no matches or multiple matches are found.

cfServices.filter(query)
// is equivalent to
_.filter(cfServices(), query)

Alternatives

Instead of this package, you can use lodash (which you probably already require in your code):

const _ = require('lodash');

var vcapServices = JSON.parse(process.env.VCAP_SERVICES);
var svc = _.keyBy(_.flatMap(vcapServices), 'name');
var redis = svc.redis1;
var postgres = _.filter(svc, {tags: ['sql']})[i];

Actually this is what this package is using internally. So why remember those APIs, when you can just use one simple function.

This package is similar to cfenv but is simpler as it is focused only on service bindings. Also this package provides easy filtering of service bindings powered by lodash filter.

License

MIT

See Also

Proposal for named service bindings