react-native-firebase/lib/modules/database/query.js

109 lines
2.0 KiB
JavaScript
Raw Normal View History

2017-03-02 11:40:08 +00:00
/**
* @flow
* Query representation wrapper
2017-03-02 11:40:08 +00:00
*/
2017-11-23 17:29:40 +00:00
import { objectToUniqueId } from '../../utils';
import type { DatabaseModifier } from '../../types';
import type Reference from './reference.js';
// todo doc methods
2017-03-02 11:40:08 +00:00
/**
* @class Query
*/
export default class Query {
_reference: Reference;
modifiers: Array<DatabaseModifier>;
2017-03-02 11:40:08 +00:00
constructor(ref: Reference, path: string, existingModifiers?: Array<DatabaseModifier>) {
2017-03-02 11:40:08 +00:00
this.modifiers = existingModifiers ? [...existingModifiers] : [];
this._reference = ref;
2017-03-02 11:40:08 +00:00
}
/**
*
* @param name
* @param key
* @return {Reference|*}
*/
orderBy(name: string, key?: string) {
this.modifiers.push({
id: `orderBy-${name}:${key || ''}`,
type: 'orderBy',
name,
key,
});
return this._reference;
2017-03-02 11:40:08 +00:00
}
/**
*
* @param name
* @param limit
* @return {Reference|*}
*/
limit(name: string, limit: number) {
this.modifiers.push({
id: `limit-${name}:${limit}`,
type: 'limit',
name,
limit,
});
return this._reference;
2017-03-02 11:40:08 +00:00
}
/**
*
* @param name
* @param value
* @param key
* @return {Reference|*}
*/
filter(name: string, value: any, key?: string) {
this.modifiers.push({
id: `filter-${name}:${objectToUniqueId(value)}:${key || ''}`,
type: 'filter',
name,
value,
valueType: typeof value,
key,
});
return this._reference;
2017-03-02 11:40:08 +00:00
}
/**
*
* @return {[*]}
*/
getModifiers(): Array<DatabaseModifier> {
2017-03-02 11:40:08 +00:00
return [...this.modifiers];
}
/**
*
* @return {*}
*/
queryIdentifier() {
// sort modifiers to enforce ordering
const sortedModifiers = this.getModifiers().sort((a, b) => {
if (a.id < b.id) return -1;
if (a.id > b.id) return 1;
return 0;
});
// Convert modifiers to unique key
let key = '{';
for (let i = 0; i < sortedModifiers.length; i++) {
if (i !== 0) key += ',';
key += sortedModifiers[i].id;
}
key += '}';
return key;
}
2017-03-02 11:40:08 +00:00
}