UNPKG

2.48 kBPlain TextView Raw
1import {IPlugin, IRepoPlugin, PluginType, IStorePlugin,
2 IIndexerPlugin, IFinderPlugin,IRepoSupportPlugin} from "./Types"
3import {Repo} from "./Repo"
4
5const Bluebird = require('bluebird')
6
7export function assert(test,msg:string = null) {
8 if (!test)
9 throw new Error(msg)
10}
11
12function isTypeOf(o,typeStr) {
13 return typeof o === typeStr
14}
15
16export function isNil(o:any) {
17 return isTypeOf(o,'undefined') || o === null
18}
19
20export function isFunction(o:any):o is Function {
21 return isTypeOf(o,'function')
22}
23
24export function isNumber(o:any):o is number {
25 return isTypeOf(o,'number')
26}
27
28export function isString(o:any):o is string {
29 return isTypeOf(o,'string')
30}
31
32export function isNumberOrString(o:any):o is string|number {
33 return isString(o) || isNumber(o)
34}
35
36export function isArrayType(type:any):boolean {
37 return type === Array ||
38 type instanceof Array ||
39 Array.isArray(type)
40}
41
42/**
43 * Check the type of a plugin
44 *
45 * @param plugin
46 * @param type
47 * @returns {boolean}
48 */
49export function isPluginOfType(plugin:IPlugin,type:PluginType):boolean {
50 return plugin.type && (plugin.type & type) > 0
51}
52
53export function isRepoPlugin(plugin:IPlugin):plugin is IRepoPlugin<any> {
54 return isPluginOfType(plugin,PluginType.Repo)
55}
56
57export function isStorePlugin(plugin:IPlugin):plugin is IStorePlugin {
58 return isPluginOfType(plugin,PluginType.Store)
59}
60
61export function isIndexerPlugin(plugin:IPlugin):plugin is IIndexerPlugin {
62 return isPluginOfType(plugin,PluginType.Indexer)
63}
64
65export function isFinderPlugin(plugin:IPlugin):plugin is IFinderPlugin {
66 return isPluginOfType(plugin,PluginType.Finder)
67}
68
69export function PromiseMap<T>(values:T[],mapper:(value:T) => any):Promise<any[]> {
70 const results = values.map(value => Promise.resolve(mapper(value)))
71 return Bluebird.all(results)
72}
73
74export function PluginFilter<P extends IPlugin>(plugins:IPlugin[],type:PluginType):P[] {
75 return plugins.filter(
76 (type == PluginType.Repo) ? isRepoPlugin :
77 (type == PluginType.Store) ? isStorePlugin :
78 (type == PluginType.Indexer) ? isIndexerPlugin :
79 isFinderPlugin
80
81 ) as P[]
82}
83
84
85export function isInstanceType<T>(val:any,type:{new():T}):val is T {
86 return val instanceof type
87}
88
89export function includesUnlessEmpty(arr:any[],val:any):boolean {
90 return arr.length === 0 || arr.includes(val)
91}
92
93export function repoAttachIfSupported(repo:Repo<any>,plugin:IRepoSupportPlugin) {
94 return (includesUnlessEmpty(plugin.supportedModels,repo.modelClazz)) ?
95 plugin.initRepo(repo) : null
96}
\No newline at end of file