Skip to content

Commit

Permalink
Merge pull request #675 from kuzzleio/7.8.0-proposal
Browse files Browse the repository at this point in the history
# [7.8.0](https://github.com/kuzzleio/sdk-javascript/releases/tag/7.8.0) (2021-12-20)


#### New features

- [ [#671](#671) ] Add Observer class   ([Aschen](https://github.com/Aschen))

#### Enhancements

- [ [#668](#668) ] Propagates every arguments to Kuzzle   ([Aschen](https://github.com/Aschen))
---
  • Loading branch information
Aschen authored Jan 3, 2022
2 parents 7cf06a5 + e2d8302 commit c32abb4
Show file tree
Hide file tree
Showing 33 changed files with 2,148 additions and 505 deletions.
3 changes: 2 additions & 1 deletion .eslintrc-ts.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"no-shadow": "off",
"@typescript-eslint/no-shadow": "error",
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/explicit-module-boundary-types": 0
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-interface": 0
}
}
121 changes: 121 additions & 0 deletions ast-refactor/inline-options-to-interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* Script to refactor inline options declaration into external interfaces
* inheriting from the default "ArgsDefault" interface.
*
* @example
*
export class SomeController {
helloWorld (
name: string,
options: {
queuable?: boolean,
timeout?: number,
age?: number;
} = {}
): string {
return name;
}
}
* This code will became
export class SomeController {
helloWorld (
name: string,
options: ArgsSomeControllerHelloWorld = {}
): string {
return name;
}
}
interface ArgsSomeControllerHelloWorld extends ArgsDefault {
age?: number;
}
*/

/* Script Arguments ==================================================== */

const filePath = process.argv[2];
const className = process.argv[3];

if (! filePath || ! className) {
console.log(`Usage: node ${process.argv[1]} <file path> <class name>`);
}

/* ===================================================================== */

import { Project, SyntaxKind, ParameterDeclaration } from 'ts-morph';

function upFirst (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

// initialize
const project = new Project({});

const file = project.addSourceFileAtPath(filePath);
const loadedClass = file.getClassOrThrow(className);

for (const method of loadedClass.getMethods()) {
if (method.getScope() !== 'public') {
continue;
}

// Get the parameter named "options"
const options = method.getParameter('options');

if (options) {
const argsInterface = createArgsInterface(method.getName(), options);

// Change the type of the "options" parameter with our newly created interface
options.setType(argsInterface.getName())
}
}


function createArgsInterface (methodName: string, options: ParameterDeclaration) {
const argsInterface = file.addInterface({
name: `Args${loadedClass.getName()}${upFirst(methodName)}`,
extends: ['ArgsDefault'],
isExported: true,
});

// Get the AST node containing the type definition
const optionsType = options.getTypeNode()

if (optionsType) {
// The SyntaxList contains properties type definitions
const syntaxList = optionsType.getChildSyntaxList();

for (const child of syntaxList.getChildren()) {

// Get the property name (e.g. "queuable")
const name = child.getChildrenOfKind(SyntaxKind.Identifier)[0].getText();
// Ignore common arguments
if (['queuable', 'timeout'].includes(name)) {
continue;
}

// Is it an optional property? (e.g. "queuable?")
const hasQuestionToken = Boolean(child.getChildrenOfKind(SyntaxKind.QuestionToken)[0]);

// Get the type of the property, the type node is located just after the "ColonToken" node
const type = child.getChildrenOfKind(SyntaxKind.ColonToken)[0].getNextSibling().getText();

argsInterface.addProperty({ name, type, hasQuestionToken });
}
}

console.log(argsInterface.getText());

return argsInterface;
}



async function run () {
await project.save();
}

run();

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,27 @@ try {

console.log(response);
/*
{ mapping:
{ policies:
{ properties:
{ restrictedTo:
{ properties:
{ collections:
{ type: 'text',
fields: { keyword: { type: 'keyword', ignore_above: 256 } } },
index:
{ type: 'text',
fields: { keyword: { type: 'keyword', ignore_above: 256 } } } } },
roleId: { type: 'keyword' } } } } }
{
"mapping": {
"policies": {
"properties": {
"roleId": {
"type": "keyword"
},
"restrictedTo": {
"properties": {
"collections": {
"type": "text"
}
},
"index": {
"type": "text"
}
}
}
},
}
}
*/
} catch (e) {
console.error(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ name: security#getProfileMapping
description: get profile mapping
template: default
expected:
- "mapping: { policies: { properties: \\[Object\\] } }"
- "mapping: { policies: { properties: \\[Object\\]"

This file was deleted.

55 changes: 55 additions & 0 deletions doc/7/core-classes/observer/get/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
code: true
type: page
title: get
description: Observer get method
---

# get

<SinceBadge version="7.8.0" />

Gets a realtime document

::: info
This method uses the [Document.get](/sdk/js/7/controllers/document/get) method under the hood to retrieve document.
:::

## Arguments

```js
get (index: string, collection: string, id: string, options: any): Promise<RealtimeDocument>
```

| Argument | Type | Description |
|----------|------|-------------|
| `index` | <pre>string</pre> | Index name |
| `collection` | <pre>string</pre> | Collection name |
| `id` | <pre>string</pre> | Document ID |
| `options` | <pre>any</pre> | Additional options |

## Usage

```js
const observer = new Observer(sdk);

const doc = await observer.get('nyc-open-data', 'yellow-taxi', 'some-id');

console.log(doc);
/*
RealtimeDocument {
_id: 'some-id',
_source: {
name: 'aschen',
age: '29',
_kuzzle_info: {
author: '-1',
createdAt: 1638432270522,
updatedAt: null,
updater: null
}
},
deleted: false
}
*/
```
6 changes: 6 additions & 0 deletions doc/7/core-classes/observer/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
code: true
type: branch
title: Observer
description: Observer class documentation
---
37 changes: 37 additions & 0 deletions doc/7/core-classes/observer/introduction/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
code: false
type: page
title: Introduction
description: Observer class
order: 0
---

# Observer

<SinceBadge version="7.8.0" />

The `Observer` class allows to manipulate realtime documents.
A `RealtimeDocument` is like a normal document from Kuzzle except that it is
connected to the realtime engine and it's content will change with changes
occuring on the database.

They can be retrieved using methods with the same syntax as in the Document
Controller:

```js
const docs = await observer.get('nyc-open-data', 'yellow-taxi', 'foobar');

const result = await observer.search('nyc-open-data', 'yellow-taxi', {
query: { exists: 'licence' }
});
```

Realtime documents are resources that should be disposed via the [Observer.stop](/sdk/js/7/core-classes/observer/stop) method otherwise subscriptions will never be terminated, documents will be kept into memory, which might lead to a memory leak.

```js
await observer.stop('nyc-open-data', 'yellow-taxi');
```

A good frontend practice is to instantiate one observer for the actual page
and/or component(s) displaying realtime documents and to dispose them when
they are not displayed anymore.
71 changes: 71 additions & 0 deletions doc/7/core-classes/observer/m-get/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
code: true
type: page
title: mGet
description: Observer mGet method
---

# mGet

<SinceBadge version="7.8.0" />


Gets multiple realtime documents.

::: info
This method uses the [Document.mGet](/sdk/js/7/controllers/document/m-get) method under the hood to retrieve documents.
:::

## Arguments

```js
mGet (index: string, collection: string, ids: string[]): Promise<{ successes: RealtimeDocument[]; errors: string[]; }>
```

| Argument | Type | Description |
|----------|------|-------------|
| `index` | <pre>string</pre> | Index name |
| `collection` | <pre>string</pre> | Collection name |
| `ids` | <pre>string[]</pre> | Document IDs |

## Usage

```js
const observer = new Observer(sdk);

const docs = await observer.get('nyc-open-data', 'yellow-taxi', ['foo', 'bar']);

console.log(docs);
/*
[
RealtimeDocument {
_id: 'foo',
_source: {
name: 'aschen',
age: '28',
_kuzzle_info: {
author: '-1',
createdAt: 1638432270522,
updatedAt: null,
updater: null
}
},
deleted: false
},
RealtimeDocument {
_id: 'bar',
_source: {
name: 'dana',
age: '30',
_kuzzle_info: {
author: '-1',
createdAt: 1638432270522,
updatedAt: null,
updater: null
}
},
deleted: false
}
]
*/
```
Loading

0 comments on commit c32abb4

Please sign in to comment.