# tintoa-data-service

> Store based data service. Handles data and saves it in files or databases as simple as possible. Extendable through different Stores

Latest version **2.3.2** (published 2019-01-12) · ISC license · 0 weekly downloads

## Install

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

## Health

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

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.3.2 |
| Published | 2019-01-12 |
| First published | 2018-05-15 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 1.9 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Christian Hiltscher |
| Maintainers | chiltscher |
| Keywords | data, database, db, service, saving, store |

## Links

- npm: https://www.npmjs.com/package/tintoa-data-service
- Repository: https://tintoa.net/plesk-git/data-service
- npm.io page: https://npm.io/package/tintoa-data-service

## Dependencies (2)

- [mongodb](https://npm.io/package/mongodb.md) ^3.1.10
- [guid-typescript](https://npm.io/package/guid-typescript.md) ^1.0.9

## Alternatives

- [angular-pipes](https://npm.io/package/angular-pipes.md) — 5.6K weekly downloads
- [@ng-web-apis/midi](https://npm.io/package/@ng-web-apis/midi.md) — 2.6K weekly downloads
- [happn-3](https://npm.io/package/happn-3.md) — 1.6K weekly downloads
- [@opensip-cli/lang-go](https://npm.io/package/@opensip-cli/lang-go.md) — 1.2K weekly downloads
- [mongoose-typescript](https://npm.io/package/mongoose-typescript.md) — 85 weekly downloads

## Recent versions

- 2.3.2 (latest) — 2019-01-12
- 2.3.1 — 2019-01-12
- 2.3.0 — 2019-01-04
- 2.2.1 — 2018-12-07
- 2.2.0 — 2018-12-07
- 2.1.0 — 2018-09-07
- 2.0.4 — 2018-08-24
- 2.0.3 — 2018-08-17
- 2.0.2 — 2018-07-20
- 2.0.1 — 2018-07-19
- 2.0.0 — 2018-07-13
- 1.1.1 — 2018-05-15
- 1.1.0 — 2018-05-15
- 1.0.0 — 2018-05-15

## README

# tintoa-data-service

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [tintoa-data-service](#tintoa-data-service)
  - [Installation](#installation)
  - [Basic Usage](#basic-usage)
    - [__DataService.save : StoreResult__](#__dataservicesave--storeresult__)
    - [__DataService.load : StoreResult__](#__dataserviceload--storeresult__)
    - [__DataService.delete : StoreResult__](#__dataservicedelete--storeresult__)
  - [enum DataService.StoreTypes](#enum-dataservicestoretypes)
  - [interface DataService.DS_Settings](#interface-dataserviceds_settings)
  - [StoreResult](#storeresult)
  - [Storable](#storable)
  - [Credentials](#credentials)
  - [Stores](#stores)
    - [FileStore](#filestore)
    - [MongoStore](#mongostore)
  - [Changelog](#changelog)


<!-- END doctoc generated TOC please keep comment here to allow auto update -->


## Installation

```bash

> npm install tintoa-data-service --save

```

## Basic Usage

To handle data with tintoa-data-service is very simple. You just need a StoreType and 3 Methods.

### __DataService.save : StoreResult__

The Code below will create new data.

```TypeScript
const service = new DataService("BaseData", DataService.StoreTypes.File);
            let result = await service.save({
                context: "User",
                data: {
                    name: "Tony Stark",
                    age: 45,
                    job: "Engineer"
                }
            });
```

Since version 2.0.2 you can use the store options to make keys unique.

```TypeScript
const service = new DataService("BaseData", DataService.StoreTypes.File);
            let result = await service.save({
                context: "User",
                data: {
                    name: "Tony Stark",
                    age: 45,
                    job: "Engineer"
                },
                options: { uniqueKeys: ["name"] },
            });
```

For updating, you need to specify the id of the existing data.

```TypeScript
            await service.save({
                context: "User",
                id: (<StoreData>result.first()).id
                data: {
                    name: "Tony Stark",
                    age: 45,
                    job: "Iron Man"
                }
            });
```

### __DataService.load : StoreResult__

Specifying the context only, the service will do a ``loadAll`` and returns all availible entries.

```TypeScript
            let data = await service.load({
                context: "User",
            });
```

Passing the id of an existing data-object as property, the data-service will load it.

```TypeScript
            let ironMan = await service.load({
                context: "User",
                id: (<StoreData>result.first()).id
            });
```

Query an entry is easy the same way - just pass the `query` object. This will return all entries that match the given query.

```TypeScript
            let ironMan = await service.load({
                context: "User",
                query: { age: 45, job: "Iron Man" }
            });
```

__NOTE:__ If you pass an id __and__ a query object, the query will always be ignored and the service will load the object with the given id.

### __DataService.delete : StoreResult__

To delete data, call the delete method and pass the id of the object to delete.
Passing an array of ids will delete multiple entries at once.

```TypeScript
            let ironMan = await service.delete({
                context: "User",
                id: (<StoreData>result.first()).id
});
```

## enum DataService.StoreTypes

The current version supports 2 types of stores.
For more information read the chapter [Stores](#stores)

    1. File-Storage:

    All the data will be saved in local files. This is a great way if you have no database connection or you are running some tests. You also can create log files or something else.

    2. MongoDB-Storage

    This will allow you to connect to a mongo-server. Its up to you to setup this server.
    You just need to pass some connection options to the DataService instance.

## interface DataService.DS_Settings

| Config name | Description |
|-----------|-------------|
| host?: string; | The host where your mongo-server is running at. |
| port?: number; | The port the server listens to. |
|user?: string;|The name of the database user|
|password?: string;|The user password|
|db_path?: string;|If you chose the FileStore, you can pass a root path for its rootDir (default: |temp)
|encode?: boolean;|If you set this to false, all files and all content will not be encrypted. |(default: true)
|jsonExtension?: boolean;|This option will let you add an json extension to the files (default: false - makes only sence if you disabled the encoding)<>

## StoreResult

Every DataService method will resolve a StoreResult object. It contains information about the CRUD process, an error message if something went wrong and an array with result data.
It also provides some methods to work with data.

| Method / Property | Type / Return type | Description |
|--|:--:|:--|
|success | boolean | ```true``` if the operation resolved, else ```false```|
|message| string| Is empty if there is no error|
|data| StoreData.DataArray | Contains the data |
|``get`` count| number | returns the number of data entries|
|toArray()| StoreData.DataObject[] | This will return an array with the plain data. No information about id or something else|
| first(query? KeyValues) | StoreData \| undefined | This will query the data array until a matching entry is found. If no query is defined, it will return the first element of the data array. It returns undefined if data is empty.|
toData() | IdData | Returns an object where each data is assigned to its id|

## Storable

Beside using an instance of a data-service directly, you can define ``storable classes``. This works only if you use TypeScript with the decorator-factory to make things happen.

```TypeScript

import { DataService, Storable } from 'tintoa-data-service';

const BaseData = new DataService("BaseData", DataService.StoreTypes.File);

@BaseData.Entity()
class User extends Storable{
    @BaseData.Property()
    public name?: string;
    @BaseData.Property()
    public age?: number;
}

let user = new User();
user.name = "Tony Stark";
user.age = 45;

await user.save();

```

For loading the objects, the Storable class has the static methods load, loadAll and find.

```TypeScript

let allUsers : User[] = User.loadAll<User>(); // returns an array with all found users;
let Tony = await User.find<User>({ name: "Tony Stark" }); // returns a single User instance.

```

## Credentials

Credentials are the way to make your saved data private. To implement this, you have to set the ``owner`` property, when you are saving the data.

```TypeScript
            await service.save({
                context: "Secret",
                data: {
                    content: "I Love Beer."
                },
                owner: "data-service developer",
                additionalCredentials: new Credentials("SUPERUSER_ROLE");
            });
```

When loading the data, you will find this entry only by passing the needed credentials.

```TypeScript

import { Credentials } from 'tintoa-data-service'

await service.load({
    context: "Secret",
    credentials: new Credentials("data-service developer")
});
await service.load({
    context: "Secret",
    credentials: new Credentials("SUPERUSER_ROLE")
});
await service.load({
    context: "Secret",
    credentials: new Credentials(["data-service developer", "SUPERUSER_ROLE"])
});
```

## Stores

### FileStore

All created data will be stored in a local files. With the ``DS_Settings.db_path`` option, you can setup a root directory for the dataservice. The default is your systems temporary directory. If you use the setting, the dataservice will create a folder ``.dataservice`` at the given location. Each dataservice instance can have its own location.
On instantiaion, it will create a directory with the given dataservice-identifier in the db_path directory. Saving with a new contex will creating a new file in the instance-directory.

Imagine the following example

```TypeScript
const settings: DataService.DS_Settings = {
    db_path: "~/dev",
    encode: false,
    jsonExtension: true
}

const BaseData = new DataService("BaseData", DataService.StoreTypes.File, settings);
const UserData = new DataService("UserData", DataService.StoreTypes.File, settings);
const AppData = new DataService("AppData", DataService.StoreTypes.File, settings);

await BaseData.save({context: "Config", data: {host: "localhost", port: 9872}});
await UserData.save({context: "Employee", data: {name: "MrRabbit",age: 77,job: "Developer"}});
await UserData.save({context: "External", data: {name: "Schorsch",age: 11,job: "Senior-Developer"}});
await AppData.save({context: "Usage", data: {registratedUsers: 2}});
```

The code above will lead to the following structure:

```bash

~/dev:
    |- .dataservice
        |- BaseData
            |- Config.json
        |- UserData
            |- Employee.json
            |- External.json
        |- AppData
            |- Usage.json

```

Now lets have a look at the settings, passed to the constructor:

- ``db_path: "~/dev"``, as already mentioned, specifies where to create the root directory.

- ``encode: false`` prevents the encoding of the data with an ``AES192`` algorithm and all the data will be saved in plain text. This may be useful for debugging or writing logfiled.

- ``jsonExtension: true`` is helpful when you disabled the data-encoding. It adds the extension '.json' to all files that your editor can deal with it.

### MongoStore

As the name says, it will save your data in a mongo database. For securing things, be sure to [setup authentication](https://docs.mongodb.com/manual/tutorial/enable-authentication/) for your database server! To setup things correctly, you have to provide the following settings:

```TypeScript
let settings : DataService.DS_Settings = {
        "host": "HOST-TO-YOUR-MONGO-SERVER",
        "port": 27017,
        "user": "USER-WITH-READ-AND-WRITE-PRIVILEGES",
        "password": "TOPSECRET"
}
```

The MonogStore Will use the same structure as the FileStore. A Dataservice instance creates a db and each context is a mongo collection.


## Changelog

__Version 2.3.1__

- fixed bug when using unique keys and credentials

__Version 2.3.0:__

- fixed bug when connecting to mongodb server
- removed unused packages

__Version 2.2.0:__

- mongodb upgrade
- using new mongodb url parser

__Version 2.1.0:__

The array elements returned by the StoreResult.toArray-method containing $id and $context now

__Version 2.0.2:__

- Considering Credentials when updating objects
- additionalCredentials parameter allows to add more credits when saving an object
- new data will be merged with the existing object on update
- introduced store options for unique keys

__Version 2.0.1:__

- You can pass a predefined id to the save method.

__Version 2.0.0:__

- It comes with the new MongoStore.

## Contact

For questions, ideas, bugs or feature requests, please write an email to hiltscher.christian@gmail.com.

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