Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(schema): Initial version of schema definitions and resolvers #2441

Merged
merged 11 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion _templates/package/new/README.md.t
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ to: packages/<%= name %>/README.md
# @feathersjs/<%= name %>

[![CI](https://github.com/feathersjs/feathers/workflows/CI/badge.svg)](https://github.com/feathersjs/feathers/actions?query=workflow%3ACI)
[![Dependency Status](https://img.shields.io/david/feathersjs/feathers.svg?style=flat-square&path=packages/socketio)](https://david-dm.org/feathersjs/feathers?path=packages/<%= name %>)
[![Dependency Status](https://img.shields.io/david/feathersjs/feathers.svg?style=flat-square&path=packages/<%= name %>)](https://david-dm.org/feathersjs/feathers?path=packages/<%= name %>)
[![Download Status](https://img.shields.io/npm/dm/@feathersjs/<%= name %>.svg?style=flat-square)](https://www.npmjs.com/package/@feathersjs/<%= name %>)

> <%= description %>
Expand Down
1,103 changes: 749 additions & 354 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/memory/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const _select = (data: any, params: any, ...args: any[]) => {
return base(JSON.parse(JSON.stringify(data)));
};

export class Service<T = any, D = Partial<any>> extends AdapterService<T, D> implements InternalServiceMethods<T> {
export class Service<T = any, D = Partial<T>> extends AdapterService<T, D> implements InternalServiceMethods<T> {
options: MemoryServiceOptions;
store: MemoryServiceStore<T>;
_uId: number;
Expand Down
22 changes: 22 additions & 0 deletions packages/schema/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2021 Feathers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

23 changes: 23 additions & 0 deletions packages/schema/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# @feathersjs/schema

[![CI](https://github.com/feathersjs/feathers/workflows/CI/badge.svg)](https://github.com/feathersjs/feathers/actions?query=workflow%3ACI)
[![Dependency Status](https://img.shields.io/david/feathersjs/feathers.svg?style=flat-square&path=packages/socketio)](https://david-dm.org/feathersjs/feathers?path=packages/schema)
[![Download Status](https://img.shields.io/npm/dm/@feathersjs/schema.svg?style=flat-square)](https://www.npmjs.com/package/@feathersjs/schema)

> A common data schema definition format

## Installation

```
npm install @feathersjs/schema --save
```

## Documentation

Refer to the [Feathers documentation](https://docs.feathersjs.com) for more details.

## License

Copyright (c) 2021 [Feathers contributors](https://github.com/feathersjs/feathers/graphs/contributors)

Licensed under the [MIT license](LICENSE).
67 changes: 67 additions & 0 deletions packages/schema/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"name": "@feathersjs/schema",
"description": "A common data schema definition format",
"version": "0.0.0",
"homepage": "https://feathersjs.com",
"main": "lib/",
"keywords": [
"feathers",
"feathers-plugin"
],
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/daffl"
},
"repository": {
"type": "git",
"url": "git://github.com/feathersjs/feathers.git"
},
"author": {
"name": "Feathers contributors",
"email": "hello@feathersjs.com",
"url": "https://feathersjs.com"
},
"contributors": [],
"bugs": {
"url": "https://github.com/feathersjs/feathers/issues"
},
"engines": {
"node": ">= 12"
},
"files": [
"CHANGELOG.md",
"LICENSE",
"README.md",
"src/**",
"lib/**",
"*.d.ts",
"*.js"
],
"scripts": {
"prepublish": "npm run compile",
"compile": "shx rm -rf lib/ && tsc",
"test": "mocha --config ../../.mocharc.json --recursive test/**.test.ts test/**/*.test.ts"
},
"directories": {
"lib": "lib"
},
"publishConfig": {
"access": "public"
},
"dependencies": {
"@feathersjs/errors": "^5.0.0-pre.9",
"@feathersjs/feathers": "^5.0.0-pre.9",
"ajv": "^8.6.2",
"json-schema": "^0.3.0",
"json-schema-to-ts": "^1.6.4"
},
"devDependencies": {
"@feathersjs/memory": "^5.0.0-pre.9",
"@types/mocha": "^9.0.0",
"@types/node": "^16.6.1",
"mocha": "^9.0.3",
"shx": "^0.3.3",
"typescript": "^4.3.5"
}
}
117 changes: 117 additions & 0 deletions packages/schema/src/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { HookContext, NextFunction } from '@feathersjs/feathers';
import { BadRequest } from '../../errors/lib';
import { Resolver } from './resolver';
import { Schema } from './schema';

const getContext = (context: HookContext) => {
return {
...context,
params: {
...context.params,
query: {}
}
}
}

export const resolveQuery = <T> (resolver: Resolver<T, HookContext>) =>
async (context: HookContext, next: NextFunction) => {
const ctx = getContext(context);
const data = context?.params?.query || {};
const query = await resolver.resolve(data, ctx, {
originalContext: context
});

context.params = {
...context.params,
query
}

return next();
};

export const resolveData = <T> (resolver: Resolver<T, HookContext>) =>
async (context: HookContext, next: NextFunction) => {
const ctx = getContext(context);
const data = context.data;
const status = {
originalContext: context
};

if (Array.isArray(data)) {
context.data = await Promise.all(data.map(current =>
resolver.resolve(current, ctx, status)
));
} else {
context.data = await resolver.resolve(data, ctx, status);
}

return next();
};

export const resolveResult = <T> (resolver: Resolver<T, HookContext>) =>
async (context: HookContext, next: NextFunction) => {
const { $resolve: properties, ...query } = context.params?.query || {};
const { resolve } = context.params;
const status = {
originalContext: context,
...resolve,
properties
};

context.params = {
...context.params,
query
}

await next();

const ctx = getContext(context);
const data = context.method === 'find' && context.result.data
? context.result.data
: context.result;

if (Array.isArray(data)) {
context.result = await Promise.all(data.map(current =>
resolver.resolve(current, ctx, status)
));
} else {
context.result = await resolver.resolve(data, ctx, status);
}
};

export const validateQuery = (schema: Schema<any>) =>
async (context: HookContext, next: NextFunction) => {
const data = context?.params?.query || {};

try {
const query = await schema.validate(data);

context.params = {
...context.params,
query
}

return next();
} catch (error: any) {
throw (error.ajv ? new BadRequest(error.message, error.errors) : error);
}
};

export const validateData = (schema: Schema<any>) =>
async (context: HookContext, next: NextFunction) => {
const data = context.data;

try {
if (Array.isArray(data)) {
context.data = await Promise.all(data.map(current =>
schema.validate(current)
));
} else {
context.data = await schema.validate(data);
}
} catch (error: any) {
throw (error.ajv ? new BadRequest(error.message, error.errors) : error);
}

return next();
};
14 changes: 14 additions & 0 deletions packages/schema/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ResolverStatus } from './resolver';

export * from './schema';
export * from './resolver';
export * from './hooks';
export * from './query';

export type Infer<S extends { _type: any }> = S['_type'];

declare module '@feathersjs/feathers/lib/declarations' {
interface Params {
resolve?: ResolverStatus<any, HookContext>;
}
}
34 changes: 34 additions & 0 deletions packages/schema/src/query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { JSONSchema } from 'json-schema-to-ts';

export const queryProperty = <T extends JSONSchema> (definition: T) => ({
oneOf: [
definition,
{
type: 'object',
additionalProperties: false,
properties: {
$gt: definition,
$gte: definition,
$lt: definition,
$lte: definition,
$ne: definition,
$in: {
type: 'array',
items: definition
},
$nin: {
type: 'array',
items: definition
}
}
}
]
} as const);

export const queryArray = <T extends readonly string[]> (fields: T) => ({
type: 'array',
items: {
type: 'string',
enum: fields
}
} as const);
Loading