-
Notifications
You must be signed in to change notification settings - Fork 639
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs(recipes): add recipe for TypeScript plugin
Closes #1589 Signed-off-by: Will Soto <willsoto@users.noreply.github.com>
- Loading branch information
Showing
1 changed file
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
# Plugins | ||
|
||
## TypeScript Example | ||
|
||
```ts | ||
export function Mixin(options = {}) { | ||
return function<T extends typeof Model>(Base: T) { | ||
return class extends Base { | ||
mixinMethod() {} | ||
}; | ||
}; | ||
} | ||
|
||
// Usage | ||
|
||
class Person extends Model {} | ||
|
||
const MixinPerson = Mixin(Person); | ||
|
||
// Or as a decorator: | ||
|
||
@Mixin | ||
class Person extends Model {} | ||
``` | ||
|
||
## TypeScript Example with Custom QueryBuilder | ||
|
||
```ts | ||
class CustomQueryBuilder<M extends Model, R = M[]> extends QueryBuilder<M, R> { | ||
ArrayQueryBuilderType!: CustomQueryBuilder<M, M[]>; | ||
SingleQueryBuilderType!: CustomQueryBuilder<M, M>; | ||
NumberQueryBuilderType!: CustomQueryBuilder<M, number>; | ||
PageQueryBuilderType!: CustomQueryBuilder<M, Page<M>>; | ||
|
||
someCustomMethod(): this { | ||
return this; | ||
} | ||
} | ||
|
||
export function CustomQueryBuilderMixin(options = {}) { | ||
return function<T extends typeof Model>(Base: T) { | ||
return class extends Base { | ||
static QueryBuilder = QueryBuilder; | ||
QueryBuilderType: CustomQueryBuilder<this, this[]>; | ||
|
||
mixinMethod() {} | ||
}; | ||
}; | ||
} | ||
|
||
// Usage | ||
|
||
class Person extends Model {} | ||
|
||
const MixinPerson = CustomQueryBuilderMixin(Person); | ||
|
||
// Or as a decorator: | ||
|
||
@CustomQueryBuilderMixin | ||
class Person extends Model {} | ||
|
||
async () => { | ||
const z = await MixinPerson.query() | ||
.whereIn('id', [1, 2]) | ||
.someCustomMethod() | ||
.where('foo', 1) | ||
.someCustomMethod(); | ||
|
||
z[0].mixinMethod(); | ||
}; | ||
``` |