# pronto-data-service

> A base Data Service with multiple DB backends and a GraphQL layer

Latest version **0.0.8-somata-peer** (published 2019-03-20) · 0 weekly downloads

## Install

```sh
npm install pronto-data-service
pnpm add pronto-data-service
yarn add pronto-data-service
bun add pronto-data-service
```

## Health

**Score 10/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; low quality score; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.8-somata-peer |
| Published | 2019-03-20 |
| First published | 2018-02-05 |
| Weekly downloads | 0 |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 9 |
| Unpacked size | 142.8 KB |
| Known vulnerabilities | 0 (+2 in 2 direct dependencies) |
| Install scripts | no |
| Author | Prontotype |
| Maintainers | brynwaldwick, chadlieberman, spro |

## Links

- npm: https://www.npmjs.com/package/pronto-data-service
- Repository: https://github.com/prontotype-us/data-service
- Homepage: https://github.com/prontotype-us/data-service#readme
- Issues: https://github.com/prontotype-us/data-service/issues
- npm.io page: https://npm.io/package/pronto-data-service

## Dependencies (9)

- [pg](https://npm.io/package/pg.md) 6.1.x
- [async](https://npm.io/package/async.md) ^2.1.4
- [qrepl](https://npm.io/package/qrepl.md) ^0.1.3
- [github](https://npm.io/package/github.md) ^12.1.0
- [aws-sdk](https://npm.io/package/aws-sdk.md) ^2.130.0
- [graphql](https://npm.io/package/graphql.md) ^0.9.1
- [mongodb](https://npm.io/package/mongodb.md) ^2.2.24
- [graphql-type-json](https://npm.io/package/graphql-type-json.md) ^0.1.4
- [graphql-type-long](https://npm.io/package/graphql-type-long.md) ^0.0.1

## Recent versions

- 0.0.8-somata-peer (latest) — 2019-03-20
- 0.1.2 — 2019-03-12
- 0.2.2 — 2018-08-21
- 0.2.1 — 2018-06-13
- 0.2.0 — 2018-05-15
- 0.0.21 — 2018-05-07
- 0.0.20 — 2018-04-23
- 0.0.19 — 2018-04-19
- 0.0.18 — 2018-04-18
- 0.0.17 — 2018-04-17
- 0.0.16 — 2018-04-17
- 0.0.15 — 2018-04-09
- 0.0.14 — 2018-03-29
- 0.0.13 — 2018-03-22
- 0.0.12 — 2018-03-22
- … 6 more at https://npm.io/package/pronto-data-service/versions

## README

# data-service

A base Data Service with multiple DB backends and a GraphQL layer

## Installation

```
$ npm install git+ssh://git@github.com/prontotype-us/data-service.git
```

## Schema

Create a file `schema.sch`

*TODO:* Document schema syntax

## Usage

A DataService is used like a regular Somata Service, with a slightly different set of arguments:

**`new DataService(service_name, db_options, custom_methods)`**

```coffee
DataService = require 'data-service'

# Create a MongoDB data service with only generic methods
new DataService 'myproject:data', {
    type: 'mongo'
    config: db: 'myprojectdb'
}

# Create a LocalDB with a specific method
new DataService 'myproject:data', {}, {doSpecificThing}
```

### Options

* `type`: Supported types are `mongo` for MongoDB, and `pg` for Postgres. Leave blank for an in-memory DB.
* `config`:
    * `id_key`: Default is always `id` (for MongoDB, IDs are coerced from `_id`).
    * Specific DB types might use extra config options:
        * `db`: Required for MongoDB and Postgres.
        * `host`: Optional for MongoDB and Postgres.
        * `user`: Optional for MongoDB and Postgres.
    * `strict_auth`: Optionally set authorization to default to `Unauthorized` without access rules

## Database Types

* MongoDb
* PostgresDb
* LocalDb: In memory database for quick testing
* ServiceDb: Forwards methods to a service that follows the data service protocol
* MultiDb: Combines multiple Dbs into one, each Db handling its own set of collections

## Methods

The base database exposes the following functions, all requiring a `type` argument (the collection name, e.g. "users"):

* `get(type, query)` &rarr; `Item`
* `find(type, query, search, options)` &rarr; `{items: [Item], total: Int, pages: Int}`
* `create(type, new_item, options)` &rarr; `Item`
* `update(type, id, item_update)` &rarr; `Item`
* `remove(type, id)` &rarr; `Bool`

### GraphQL methods

* `query(query, context...)`

The base `query` method takes a GraphQL query that may represent a get, find, create, or update, and one or more objects of arguments to pass to the query. 

#### Get

Get a single item with either `id` or `query` argument:

```
query($id: ID) {
    user(id: $id) {id, name, email}
}
```

```
query($email: String) {
    user(query: {email: $email}) {id, name, email}
}
```

#### Find

Find multiple items, paginated, with a `query`. Note that the items are wrapped in another object with the shape `{items, total, pages}`. You can pass an `options` with `{page}` for pagination:

```
query($city: String, $page: Int) {
    users(query: {city: $city}, options: {page: $page}) {items {id, name, email}, total}
}
```

#### Create

Mutation query with argument `create`, which returns the created item:

```
mutation($name: String, $email: String) {
    create_user(create: {name: $name, email: $email}) {id, name, email}
}
```

#### Update

Mutation query with arguments `id` and `update`, which returns the updated item:

```
mutation($id: ID, $name: String) {
    update_user(id: $id, update: {name: $name}) {id, name}
}
```

## Subscriptions

By passing a GraphQL query as second subscription argument you can specify the shape of the event to be returned. The query needs an `id` argument which will use the created or updated item's `id`.

```coffee
task_query = '''
query($id: ID){
    task(id: $id){id, name}
}
'''

client.subscribe 'sconce:data', 'tasks:5:updated', task_query, ({task}) ->
    console.log '[specific task updated, graphql]', task
```

Without a query, you'll get the object as it is returned from the Db class.

```coffee
client.subscribe 'sconce:data', 'tasks:created', (task) ->
    console.log '[any task created, raw]', task
```

## Triggers

Attach extra actions before and after creates and updates using triggers, passed as a config argument in the shape `{collection: {postCreate: fn, ...}, ...}`. Available actions are `preCreate`, `postCreate`, and `postUpdate`.

```coffee
triggers = {
    tasks: {
        postCreate: (created_task) ->
            console.log 'Look at this task', created_task
    }
}
```

## Authorization

Optionally configure authorization for each type with three dictionaries. By default users will be authorized to perform all actions.

```coffee
canUpdate = {
    '[type]': (user_id, item_id, cb) ->
        authorized = true # Bool
        cb err, authorized
}
canCreate = {
    '[type]': (user_id, new_item, cb) ->
        cb err, true
}
canRead = {
    '[type]': (user_id, item, cb) ->
        cb err, true
}
```

You can set the authorization to default to Unauthorized unless a successful access rule is specified with `config.strict_auth = true`.

The service will then offer an authorized version of each generic method, with a user_id as an additional first argument.

```coffee
createAs = (user_id, args...) ->
    # optional type-wise canCreate
    @create args...

getAs = (user_id, args...) ->
    # optional type-wise canRead
    @get args...

findAs = (user_id, args...) ->
    # optional type-wise canRead
    @find args...

updateAs = (user_id, args...) ->
    # optional type-wise canUpdate
    @update args...

queryAs = (user_id, query, context) ->
    # substitute getAs, findAs for get, find...
    query query, context

# Create a LocalDB with some triggers and access rules
new DataService 'myproject:data', {
    config: {
        triggers
        canRead:
            tasks: (user_id, item, cb) ->
                get 'users', {id: user_id}, (err, user) ->
                    cb err, user.god == true ||
                        user_id in item.assigned_user_ids
        canUpdate:
            tasks: (user_id, item_id, cb) ->
                get 'users', {id: user_id}, (err, user) ->
                    cb err, user.god
    }
}
```

## Db Subclasses

Implement these methods:

```coffee
Db = require './db'

class CustomDb extends Db
    _get: (type, query, cb) ->
    _find: (type, query, search, options, cb) ->
    _findWithArray: (type, queries, cb) ->
    _create: (type, new_item, cb) ->
    _update: (type, id, item_update, cb) ->
    _remove: (type, id, cb) ->
```

---
_Source: https://npm.io/package/pronto-data-service · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
