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

feathers-postgresql

v1.0.1

Published

Feathers Postgres service

Downloads

15

Readme

feathers-postgres

NPM

Build Status Code Climate

Create a Postgres service for FeathersJS

Getting Started

To install feathers-hooks from npm, run:

$ npm install feathers-postgres --save

Creating an Postgres service is this simple:

var mongoService = require('feathers-postgres');
app.use('todos', mongoService('todos', options));

Complete Example

Here's a complete example of a Feathers server with a todos postgres-service.

// server.js
var feathers = require('feathers'),
  bodyParser = require('body-parser'),
  mongoService = require('feathers-mongo');

// Create a feathers instance.
var app = feathers()
  // Setup the public folder.
  .use(feathers.static(__dirname + '/public'))
  // Enable Socket.io
  .configure(feathers.socketio())
  // Enable REST services
  .configure(feathers.rest())
  // Turn on JSON parser for REST services
  .use(bodyParser.json())
  // Turn on URL-encoded parser for REST services
  .use(bodyParser.urlencoded({extended: true}))

// Connect to the db, create and register a Feathers service.
app.use('todos', new mongoService('todos'));

// Start the server.
var port = 8080;
app.listen(port, function() {
    console.log('Feathers server listening on port ' + port);
});

You can run this example by using node examples/basic and going to localhost:8080/todos. You should see an empty array. That's because you don't have any Todos yet but you now have full CRUD for your new todos service!

Options

The following options can be passed when creating a new Postgres service:

General options:

  • connectionString - A Postgres connection string
  • _id - The id property (default: "_id")

Connection options: (when connectionString is not set)

  • db - The name of the database (default: "feathers")
  • host - The Postgres host (default: "localhost")
  • port - The Postgres port (default: 27017)
  • username - Postgres username
  • password - Postgres password
  • reconnect - Whether the connection should automatically reconnect (default: true)

Postgres options:

  • w - Write acknowledgments (default: 1)
  • journal - Don't wait for journal before acknowledgment (default: false)
  • fsync - Don't wait for syncing to disk before acknowledgment (default: false)
  • safe - Safe mode (default: false)

Sharing a Postgres connection between services

When creating a new service, the default behavior is to create a new connection to the specified database. If you would rather share a database connection between multiple services, connect to the database then pass an already-connected collection object in on options.collection. For example:

var feathers = require('feathers')
  , mongo = require('mongoskin')
  , mongoService = require('feathers-mongodb')
  , app = feathers();

// First, make the connection.
var db = mongo.db('mongodb://localhost:27017/my-project');

// Use the same db connection in both of these services.
app.use('/api/users', mongoService({collection:db.collection('users')}));
app.use('/api/todos', mongoService({collection:db.collection('todos')}));

app.listen(8080);

Extending Postgres services

To extend the basic Postgres service there are two options. Either through using Uberproto's inheritance mechanism or by using feathers-hooks.

With Uberproto

The basic Postgres Feathers service is implemented using Uberproto, a small EcmaScript 5 inheritance library so you can use the Uberproto syntax to add your custom functionality. For example, you might want update and patch to behave the same (the basic implementation of update replaces the entire object instead of merging it) and add an updatedAt and createdAt flag to your data:

// myservice.js
var mongodb = require('feathers-mongodb');
var Proto = require('uberproto');

var TimestampPatchService = mongodb.Service.extend({
  create: function(data, params, callback) {
    data.createdAt = new Date();
    
    // Call the original `create`
    return this._super(data, params, callback);
  },
  
  update: function() {
    // Call `patch` instead so that PUT calls merge
    // instead of replace data, too
    this.patch(id, data, params, callback);
  },
  
  patch: function(id, data, params, callback) {
    data.updatedAt = new Date();
    
    // Call the original `patch`
    this._super(id, data, params, callback);
  }
});

// Export a simple function that instantiates this new service like
// var myservice = require('myservice');
// app.use('/users', myservice(options));
module.exports = function(options) {
  // We need to call `Proto.create` explicitly here since we are overriding
  // the original `create` method
  return Proto.create.call(TimestampPatchService, options);
}

module.exports.Service = TimestampPatchService;

With hooks

Another option is to weave functionality into your existing services using feathers-hooks, for example the above createdAt and updatedAt functionality:

var feathers = require('feathers');
var hooks = require('feathers-hooks');
var mongodb = require('feathers-mongodb');

// Initialize a Postgres service with the users collection on a local Postgres instance
var app = feathers()
  .configure(hooks())
  .use('/users', mongodb({
    collection: 'users'
  }));
  
app.lookup('users').before({
  create: function(hook, next) {
    hook.data.createdAt = new Date();
    next();
  },
  
  update: function(hook, next) {
    hook.data.updatedAt = new Date();
    next();
  }
});

app.listen(8080);

Special Query Params

The find API allows the use of $limit, $skip, $sort, and $select in the query. These special parameters can be passed directly inside the query object:

// Find all recipes that include salt, limit to 10, only include name field.
{"ingredients":"salt", "$limit":10, "$select":"name:1"} // JSON
GET /?ingredients=salt&%24limit=10&%24select=name%3A1 // HTTP

As a result of allowing these to be put directly into the query string, you won't want to use $limit, $skip, $sort, or $select as the name of fields in your document schema.

$limit

$limit will return only the number of results you specify:

// Retrieves the first two records found where age is 37.
query: {
  age: 37,
  $limit: 2
}

$skip

$skip will skip the specified number of results:

// Retrieves all except the first two records found where age is 37.
query: {
  age: 37,
  $skip: 2
}

$sort

$sort will sort based on the object you provide:

// Retrieves all where age is 37, sorted ascending alphabetically by name.
query: {
  age: 37,
  $sort: {'name': 1}
}

// Retrieves all where age is 37, sorted descending alphabetically by name.
query: {
  age: 37,
  $sort: {'name': -1}
}

$select

$select support in a query allows you to pick which fields to include or exclude in the results. Note: you can use the include syntax or the exclude syntax, not both together. See the section on Select in the Mongoose docs.

// Only retrieve name.
query: {
  name: 'Alice',
  $select: {'name': 1}
}

// Retrieve everything except age.
query: {
  name: 'Alice',
  $select: {'age': 0}
}

API

feathers-mongodb services comply with the standard FeathersJS API.

Changelog

1.0.0

  • makes this adapter consistent with the others in terms of documentation and file structure
  • updates mongoskin dependency to the latest
  • adds support for special query filters
    • $sort
    • $select
    • $skip
    • $limit
  • Closes #8 by making sure that we autoreconnect by default when not passing a connection string

0.3.0

  • Implement .patch support (#5)
  • Better documentation
  • Refactoring that removes pre-implemented MongoSkin options

0.2.x

  • Pre-releases

License

MIT

Authors