# Utils

Source: https://developers.inkdrop.app/data-access/utils

Provides convenient methods for managing documents in the local database.

---

## Search for notes `search(keyword, options)`

Retrieves notes which match given keyword.

### Parameters

- **keyword** (string, required)

  The search keyword. The syntax is described [here](https://docs.inkdrop.app/manual/searching-notes).
- **options** (object)

  Options include sorting, limiting, and skipping notes.
  - **sort** (object\[])

    An array of objects, each indicating a field and order.
    Supported fields are: `'rank'`, `'title'`, `'updatedAt'`, `'createdAt'` and `'tagCount'`.
    See [notes.all](https://developers.inkdrop.app/data-access/notes#list-all-notes) for `'tagCount'`.
    `'rank'` sorts by relevance, best first when ascending.
    It requires the keyword to contain words to match, and throws an error if the keyword consists only of qualifiers such as `book:` or `tag:`.
    Example: `[ { rank: 'asc' } ]`, `[ { updatedAt: 'asc' } ]`.
    Default: `[ { rank: 'asc' } ]` if the keyword contains words to match, otherwise `[ { updatedAt: 'desc' } ]`.
  - **pinnedFirst** (boolean)

    Whether to list pinned notes first. It has no effect when sorting by `'rank'`. Default is `true`.
  - **limit** (number | false)

    Number of notes to fetch. Pass `false` to fetch all matching notes. Default is `50`.
  - **skip** (number)

    Number of notes to skip. Default is `0`.
  - **includeDocs** (boolean)

    Whether the result rows include the note documents. When `false`, each row contains only the note's `id` and `rev`. Default is `true`.
  - **highlightMatches** (boolean)

    Whether to return where the keyword matched in each note's title and body.
    Default is `true` when `options` is omitted, and `false` otherwise.

### Returns

Returns a query result with matching notes.
The notes are in `rows`, each as `rows[].doc`.
With `highlightMatches`, each row also has `extra.fts`, which contains `titleHighlights` and `bodyHighlights`.
Each highlight has `offStart` and `offEnd`, the offsets in the whole text, and `line`, `chStart` and `chEnd`, the position within its line.

```js
const db = env.localDB
const results = await db.utils.search('foobar', {
  sort: [ { updatedAt: 'asc' } ],
  limit: 20,
  highlightMatches: true
})
```

```js title="Response"
{
  "query": {
    "sort": [ { "updatedAt": "asc" } ],
    "limit": 20,
    "highlightMatches": true,
    "index": "fts",
    "conditions": [
      {
        "type": "keyword",
        "term": "foobar",
        "phrase": false,
        "exclude": false
      }
    ]
  },
  "totalRows": Infinity,
  "cursor": {
    "sort": [ { "updatedAt": "asc" } ],
    "limit": 20,
    "skip": 20,
    "highlightMatches": true,
    "index": "fts",
    "conditions": [
      {
        "type": "keyword",
        "term": "foobar",
        "phrase": false,
        "exclude": false
      }
    ]
  },
  "includeDocs": true,
  "rows": [
    {
      "doc": {
        "doctype": "markdown",
        "updatedAt": 1461564004766,
        "createdAt": 1461563995746,
        "bookId": "book:32b385767dc2",
        "status": "none",
        "numOfTasks": 0,
        "numOfCheckedTasks": 0,
        "title": "foobar",
        "body": "body...",
        "_id": "note:4eeb997c",
        "_rev": "8-d18201be3336c70979c6a375b497b3a7"
      },
      "extra": {
        "fts": {
          "titleHighlights": [
            { "offStart": 0, "offEnd": 6, "line": 0, "chStart": 0, "chEnd": 6 }
          ],
          "bodyHighlights": []
        }
      }
    },
    ...
  ]
}
```

---

## Delete a tag `deleteTag(tagId)`

Delete a tag with the specified ID and remove it from associated notes.

### Parameters

- **tagId** (string, required)

  The tag ID to delete.

### Returns

A Promise that will reject if the tag cannot be deleted.

```js
const db = env.localDB
await db.utils.deleteTag('tag:tBELDUITs')
```

---

## Move a note to a notebook `moveNoteToBook(noteId, moveToBookId)`

Move a note to a designated notebook.

### Parameters

- **noteId** (string, required)

  The note ID you wish to move.
- **moveToBookId** (string, required)

  The destination notebook ID where the note will be moved to.

### Returns

Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Rejects if there's a failure in moving the note.

```js
const db = env.localDB
await db.utils.moveNoteToBook('note:BKzzd8iGK', 'book:4eeb997c')
```

---

## Move multiple notes to a notebook `moveNoteToBookBatch(noteIds, moveToBookId)`

Move a batch of notes to a designated notebook.

### Parameters

- **noteIds** (array, required)

  An array of note IDs you wish to move.
- **moveToBookId** (string, required)

  The destination notebook ID where the notes will be moved to.

### Returns

Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Rejects if there's a failure in moving the notes.

```js
const db = env.localDB
await db.utils.moveNoteToBookBatch(["note:BKzzd8iGK", "note:8eea9f7c"], 'book:4eeb997c')
```

---

## Duplicate a note `duplicateNote(noteId)`

Duplicate a note with the provided note ID. The duplicated note will have newly assigned values for `_id`, `createdAt`, `updatedAt`, and `_rev`.

### Parameters

- **noteId** (string, required)

  The ID of the note you wish to duplicate.

### Returns

Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which will resolve with the duplicated note details.

```js
const db = env.localDB
await db.utils.duplicateNote("note:BKzzd8iGK")
```

---

## Duplicate multiple notes `duplicateNoteBatch(noteIds)`

Duplicate a batch of notes. Each duplicated note will have newly assigned values for `_id`, `createdAt`, `updatedAt`, and `_rev`.

### Parameters

- **noteIds** (array, required)

  An array of note IDs you wish to duplicate.

### Returns

Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which will resolve with the details of the duplicated notes.

```js
const db = env.localDB
await db.utils.duplicateNoteBatch(["note:BKzzd8iGK", "note:8eea9f7c"])
```

---

## Trash or delete multiple notes `moveNotesToTrashOrDelete(noteIds)`

Move the given notes to trash or if they are already in the trash, delete them permanently.

### Parameters

- **noteIds** (array, required)

  An array of note IDs to either move to trash or delete permanently.

### Returns

Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Rejects if it fails to perform any of the operations.

```js
const db = env.localDB
await db.utils.moveNotesToTrashOrDelete(["note:BKzzd8iGK", "note:8eea9f7c"])
```

---

## Empty Trash `emptyTrash()`

Delete notes in trash permanently.

### Returns

Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which rejects if failed to empty trash.

```js
const db = env.localDB
await db.utils.emptyTrash()
```

---

## Set Tags Batch `setTagsBatch(noteIds, tags)`

Sets given tags to notes with specified IDs.

### Parameters

- **noteIds** (array, required)

  A list of IDs of notes to be set.
- **tags** (array of string, required)

  A list of tag IDs to set.

### Returns

Returns an Array of updated [Note](https://developers.inkdrop.app/notes)s.

```js
const db = env.localDB
await db.utils.setTagsBatch(["note:BKzzd8iGK", "note:8eea9f7c"], ["tag:tBELDUITs"])
```

---

## Set Status Batch `setStatusBatch(noteIds, status)`

Sets specified note status to notes with given IDs.

### Parameters

- **noteIds** (array, required)

  A list of IDs of notes to be set.
- **status** (string, required)

  A note status which can be `'none'`, `'active'`, `'onHold'`, `'completed'` or `'dropped'`.

```js
const db = env.localDB
await db.utils.setStatusBatch(["note:BKzzd8iGK", "note:8eea9f7c"], "completed")
```

---

## Move a notebook `moveBook(bookId, newParentBookId)`

Sets a notebook with specified ID as a child of a notebook.

### Parameters

- **bookId** (string, required)

  A notebook ID to move.
- **newParentBookId** (string or null)

  A notebook ID of new parent notebook. Specifying `null` moves the notebook to the root.

### Returns

Returns the updated [Book](https://developers.inkdrop.app/books).

```js
const db = env.localDB
await db.utils.moveBook("book:tjnPbJakw", "book:Bk5Ivk0T")
```

---

## Delete a notebook `deleteBook(bookId)`

Deletes a notebook with given ID and moves notes associated with it into trash.

### Parameters

- **bookId** (string, required)

  A notebook ID to delete.

### Returns

Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

```js
const db = env.localDB
await db.utils.deleteBook("book:tjnPbJakw")
```

---

## Get Buffer From File `getBufferFromFile(fileId)`

Loads an image file as [Buffer](https://nodejs.org/api/buffer.html#buffer_buffer).

### Parameters

- **fileId** (string, required)

  A file ID to load.

### Returns

Returns a content of the image file.

```js
const db = env.localDB
await db.utils.getBufferFromFile("file:5c2c2b2c")
```
