Skip to content

Commit

Permalink
docs(README): fix code sample and describe forPrimitives (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
forivall authored Oct 18, 2024
1 parent c37d305 commit b636ba6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Before you submit your Pull Request (PR) consider the following guidelines:
npx pnpm add -g pnpm
cd ucast
pnpm recursive i
pnpm build -r
pnpm -r build
```

* Make your changes in a new git branch (fork master branch):
Expand Down
37 changes: 32 additions & 5 deletions packages/mongo2js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,24 +76,33 @@ In order to implement a custom operator, you need to create a [custom parsing in
This package re-exports all symbols from `@ucast/mongo` and `@ucast/js`, so you don't need to install them separately. For example, to add support for [json-schema](https://json-schema.org/) operator:

```ts
import { createFilter } from '@ucast/mongo2js';
import {
createFactory,
DocumentCondition,
ParsingInstruction,
JsInterpreter,
} from '@ucast/mongo2js';
import Ajv from 'ajv';

const $jsonSchema = {
type JSONSchema = object;
const ajv = new Ajv();
const $jsonSchema: ParsingInstruction<JSONSchema> = {
type: 'document',
validate(instruction, value) {
if (!value || typeof value !== 'object') {
throw new Error(`"${instruction.name}" expects to receive an object`)
}
},
parse(instruction, schema) {
const ajv = new Ajv();
return new DocumentCondition(instruction.name, ajv.compile(schema));
}
};
const jsonSchema = (condition, object) => condition.value(object);
const jsonSchema: JsInterpreter<DocumentCondition<Ajv.ValidateFunction>> = (
condition,
object
) => condition.value(object) as boolean;

const customGuard = createFilter({
const customGuard = createFactory({
$jsonSchema,
}, {
jsonSchema
Expand All @@ -105,12 +114,30 @@ const test = customGuard({
firstName: { type: 'string' },
lastName: { type: 'string' },
},
required: ['firstName', 'lastName'],
}
});

console.log(test({ firstName: 'John' })); // false, `lastName` is not defined
```

To create a custom operator which tests primitives (as `squire` does), use the
`forPrimitives` option:

```ts
const customSquire = createFactory({
$custom: {
type: 'field',
}
}, {
custom: (condition, value) => value === (condition.value ? 'on' : 'off')
}, {
forPrimitives: true
});
const test = customGuard({ $custom: true });
console.log(test('on')) // true
```

## TypeScript support

This package is written in TypeScript and supports type inference for MongoQuery:
Expand Down

0 comments on commit b636ba6

Please sign in to comment.