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

Extended defineTypes with filters #126

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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 src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export abstract class Schema {
console.error(e);
}

static is(type: DefinitionType) {
static is(type: DefinitionType): type is typeof Schema {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not related but useful for type inference

return (
type['_definition'] &&
type['_definition'].schema !== undefined
Expand Down
37 changes: 37 additions & 0 deletions src/annotations/Context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { DefinitionType, SchemaDefinition, type } from '.';
import { Schema } from '../Schema';

// Colyseus integration
export type ClientWithSessionId = { sessionId: string } & any;

export class Context {
types: {[id: number]: typeof Schema} = {};
schemas = new Map<typeof Schema, number>();
useFilters = false;

has(schema: typeof Schema) {
return this.schemas.has(schema);
}

get(typeid: number) {
return this.types[typeid];
}

add(schema: typeof Schema, typeid: number = this.schemas.size) {
// FIXME: move this to somewhere else?
// support inheritance
schema._definition = SchemaDefinition.create(schema._definition);

schema._typeid = typeid;
this.types[typeid] = schema;
this.schemas.set(schema, typeid);
}

static create(context: Context = new Context) {
return function (definition: DefinitionType) {
return type(definition, context);
}
}
}

export const globalContext = new Context();
105 changes: 105 additions & 0 deletions src/annotations/SchemaDefinition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { FilterCallback, FilterChildrenCallback } from '.';
import { getType } from '../types';
import { Schema } from '../Schema';

/**
* Data Types
*/

export type PrimitiveType =
"string" |
"number" |
"boolean" |
"int8" |
"uint8" |
"int16" |
"uint16" |
"int32" |
"uint32" |
"int64" |
"uint64" |
"float32" |
"float64" |
typeof Schema;

export type DefinitionType = PrimitiveType
| [PrimitiveType]
| { array: PrimitiveType }
| { map: PrimitiveType }
| { collection: PrimitiveType }
| { set: PrimitiveType };

export type Definition = { [field: string]: DefinitionType };

export class SchemaDefinition {
schema: Definition;

//
// TODO: use a "field" structure combining all these properties per-field.
//

indexes: { [field: string]: number } = {};
fieldsByIndex: { [index: number]: string } = {};

filters: { [field: string]: FilterCallback };
indexesWithFilters: number[];
childFilters: { [field: string]: FilterChildrenCallback }; // childFilters are used on Map, Array, Set items.

deprecated: { [field: string]: boolean } = {};
descriptors: PropertyDescriptorMap & ThisType<any> = {};

static create(parent?: SchemaDefinition) {
const definition = new SchemaDefinition();

// support inheritance
definition.schema = Object.assign({}, parent && parent.schema || {});
definition.indexes = Object.assign({}, parent && parent.indexes || {});
definition.fieldsByIndex = Object.assign({}, parent && parent.fieldsByIndex || {});
definition.descriptors = Object.assign({}, parent && parent.descriptors || {});
definition.deprecated = Object.assign({}, parent && parent.deprecated || {});

return definition;
}

addField(field: string, type: DefinitionType) {
const index = this.getNextFieldIndex();
this.fieldsByIndex[index] = field;
this.indexes[field] = index;
this.schema[field] = (Array.isArray(type))
? { array: type[0] }
: type;
}

addFilter(field: string, cb: FilterCallback) {
if (!this.filters) {
this.filters = {};
this.indexesWithFilters = [];
}
this.filters[this.indexes[field]] = cb;
this.indexesWithFilters.push(this.indexes[field]);
return true;
}

addChildrenFilter(field: string, cb: FilterChildrenCallback) {
const index = this.indexes[field];
const type = this.schema[field];

if (getType(Object.keys(type)[0])) {
if (!this.childFilters) { this.childFilters = {}; }

this.childFilters[index] = cb;
return true;

} else {
console.warn(`@filterChildren: field '${field}' can't have children. Ignoring filter.`);
}
}

getChildrenFilter(field: string) {
return this.childFilters && this.childFilters[this.indexes[field]];
}

getNextFieldIndex() {
return Object.keys(this.schema || {}).length;
}
}
33 changes: 33 additions & 0 deletions src/annotations/defineTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { DefinitionType, filter, FilterCallback, filterChildren, FilterChildrenCallback, type } from '.';
import { Schema } from '../Schema';
import { ArraySchema } from '../types/ArraySchema';
import { MapSchema } from '../types/MapSchema';
import { Context, globalContext } from './Context';

export type DefinitionTypeOptions<S extends Schema, R extends Schema, P = any, K = any, V = any> = {
type: DefinitionType;
filter?: FilterCallback<S, P, R>;
filterChildren?: FilterChildrenCallback<S, K, V, R>;
}

const isPrimitiveType = (type: any) => typeof type === "string" || Schema.is(type);
const isDefinitionType = (type: any): type is DefinitionType => isPrimitiveType(type) || ArraySchema.is(type) || MapSchema.is(type) || type["type"] == null;
export function defineTypes<S extends Schema = any, R extends Schema = any>(
target: typeof Schema,
fields: {
[property: string]: DefinitionType | DefinitionTypeOptions<S, R>
},
context: Context = target._context || globalContext
) {
for (let fieldName in fields) {
const field = fields[fieldName];
if (isDefinitionType(field)) {
type(field, context)(target.prototype, fieldName);
continue;
}
type(field.type, context)(target.prototype, fieldName);
if (field.filter) filter(field.filter)(target.prototype, fieldName)
if (field.filterChildren) filterChildren(field.filter)(target.prototype, fieldName)
}
return target;
}
Loading