# csh-file-formatter-module

> Module to format JSON with common transformations

Latest version **1.2.2** (published 2019-06-25) · ISC license · 0 weekly downloads

## Install

```sh
npm install csh-file-formatter-module
pnpm add csh-file-formatter-module
yarn add csh-file-formatter-module
bun add csh-file-formatter-module
```

## Health

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

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.2.2 |
| Published | 2019-06-25 |
| First published | 2019-06-12 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 13 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | mssnews |
| Maintainers | mss-npm-user |
| Keywords | format, json, newsource |

## Links

- npm: https://www.npmjs.com/package/csh-file-formatter-module
- Repository: https://github.com/turnercode/csh-file-formatter-module
- Homepage: https://github.com/turnercode/csh-file-formatter-module#readme
- Issues: https://github.com/turnercode/csh-file-formatter-module/issues
- npm.io page: https://npm.io/package/csh-file-formatter-module

## Dependencies (1)

- [json-map-transform](https://npm.io/package/json-map-transform.md) 1.2.5

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 1.2.2 (latest) — 2019-06-25
- 1.2.1 — 2019-06-12
- 1.2.0 — 2019-06-12
- 1.1.0 — 2019-06-12

## README

# csh-file-formatter-module

Wrapper around [json-map-transformer](https://www.npmjs.com/package/json-map-transform) to map JSON objects using common transformations.

## Installation

```bash
npm i csh-file-formatter-module
```

## Usage

```js
const { JSONTransformer } = require('csh-file-formatter-module');

const formater = new JSONTransformer(template, staticKeys, configOptions);

console.log(formater.transform(obj, afterTransform))
```

### Template

**key**: Property name on the output object

**path**: Property in the input object that will be mapped. Can also be an array of possible paths. Can be omitted if the key will be the same.

**transform**: Function that receives input value/Name of a predefined transformation function. Can be an array of mixed values.

**default**: Value to set if the transformed value is `undefined`. Can also be a function that will be executed when the JSONTransformer is created.

After transformation, `undefined` and empty strings are omitted.

Example:

```js
{
    timestamp: {
        path: 'updatedAt',
        transform: 'LOCALE_STRING'
    },
    name: 'author', // same as { path: 'author', omit: ['', undefined] },
    id: {
        transform: (id) => id + '123'
    },
    description: {
        transform: ['NORMALIZE', (description) => description.replace('a', 'e')] // normalize(description).replace(...)
    }
}
```

#### Transformations

The following transformations are predefined:

| name          | description |
| ------------- | ----------- |
| **Strings** |
| NORMALIZE_ALL | Replace `:` with `_` and spaces with `-` |
| NORMALIZE     |  Replace spaces with `-` |
| UPPERCASE     |  Converts string to uppercase |
| LOWERCASE     |  Converts string to lowercase∫ |
| MAX_CHARS     |  Returns substring(0, _maxChars_) |
| TAGS_NORM     |  Removes tags from string |
| SPACES_NORM     |  Removes `\\n` and `\\r` characters with single space. Also removes multiple spaces with single one |
| HTML_NORM     | Replaces HTML entities to proper char, removes unicode and special chars |
| **URLs** |
| URL_ORIGIN    | Returns origin from an url |
| URL_PATH      |  Returns path from an url |
| **Dates** |
| LOCALE_STRING | Transform string date to locale string date (within timezone specified) |
| YEAR_MONTH    | Gets `YYYYMM` format from a ISO string date |
| ISO_STRING    | Returns ISO string from a date |
| SPLIT_TIMESTAMP | Given a ISO date or UNIX timestamp, returns an array with date components |

### Static Keys

Object with values to add to the output object. Each key must be a value or function. In case of functions, they are evaluated each time `transform` is executed.

Example:

```js
{
    origin: 'a value',
    number: () => 5 
}
```

### Config options

There are possible variables to configure:

- **maxChars**. Sets the value for `MAX_CHARS` transformation. Defaults to 260000.
- **timezone**. Time zone used for `LOCALE_STRING` transformation.
- **keepUnused**. Boolean to indicate the unused fields from original object should be kept. The fields unused are stored on _unusedFieldsKey_ key and are transformed with `JSON.stringify` (see _stringifyUnused_). Defaults to `false`.
- **unusedFieldsKey**. Name of the key where the unused fields are stored. Defaults to `meta`. If the value passed is `.` the unused keys will be added in the output object.
- **stringifyUnused**. Indicates if the unused fields should be stringified or not. Defaults to `true`.
- **afterTransform**. Function that will receive the output object and process it. Can be overrided on the `transform` method. Defaults to: `x => x`.

### .transform(obj, afterTransform)

#### Params

**obj**: Object to be transformed

**afterTransform**: Function to be used on the transformation. Defaults to `configOptions.afterTransform`

Example:

```js
myTransformer.transform(obj, (outputObj, inputObject) => {
    outputObj.processed = 1 + inputObject.count;
    return outputObj;
})
```

## Example

```js
const { JSONTransformer } = require('csh-file-formatter-module');

const template = {
    slug: {
        transform: ['NORMALIZE', 'UPPERCASE']
    },
    description: 'details',
    url: {
        path: 'source.url',
        transform: 'URL_ORIGIN'
    },
    author: {
        transform: author => 'By ' + author
    },
    date: {
        path: 'created_at',
        transform: 'LOCALE_STRING'
    }
};

const staticKeys = {
    source: 'json-map-transform',
    id: () => {
        return 'addd';
    }
}

const configOpts = {
    keepUnused: true,
    timezone: 'America/Bogota'
}

function afterTransform(outputObj) {
    outputObj.identifier = `${outputObj.slug}-${outputObj.id}`;
    return outputObj;
}

const formater = new JSONTransformer(template, staticKeys, configOpts);
const output = formater.transform({
    slug: 'a new challenge',
    details: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tempor.',
    source: {
        url: 'https://es.lipsum.com/feed/html',
        provider: 'lipsum'
    },
    author: 'sit amet',
    location: 'Spain',
    created_at: '2019-05-03T11:15:43Z'
}, afterTransform);

// output = 
// {
//   slug: 'A-NEW-CHALLENGE',
//   description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tempor.',
//   url: 'https://es.lipsum.com',
//   author: 'By sit amet',
//   date: '05/03/2019, 06:15:43',
//   meta: '{"source":{"url":"https://es.lipsum.com/feed/html","provider":"lipsum"},"location":"Spain"}',
//   source: 'json-map-transform',
//   id: 'cc612cda-1535-4221-b7f8-f86259689562'
//   identifier: 'A-NEW-CHALLENGE-cc612cda-1535-4221-b7f8-f86259689562'
// }
```

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