advancing well

This commit is contained in:
David Lebee
2019-12-06 12:41:28 -06:00
parent c1d56d0c19
commit 0adaa73439
18 changed files with 653 additions and 74 deletions
@@ -0,0 +1,24 @@
# NgxDataApollo
This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.2.4.
## Code scaffolding
Run `ng generate component component-name --project ngx-data-apollo` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project ngx-data-apollo`.
> Note: Don't forget to add `--project ngx-data-apollo` or else it will be added to the default project in your `angular.json` file.
## Build
Run `ng build ngx-data-apollo` to build the project. The build artifacts will be stored in the `dist/` directory.
## Publishing
After building your library with `ng build ngx-data-apollo`, go to the dist folder `cd dist/ngx-data-apollo` and run `npm publish`.
## Running unit tests
Run `ng test ngx-data-apollo` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
@@ -0,0 +1,32 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../../coverage/poweredsoft/ngx-data-apollo'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
@@ -0,0 +1,7 @@
{
"$schema": "../../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../../dist/poweredsoft/ngx-data-apollo",
"lib": {
"entryFile": "src/public-api.ts"
}
}
@@ -0,0 +1,15 @@
{
"name": "@poweredsoft/ngx-data-apollo",
"version": "0.0.1",
"peerDependencies": {
"@poweredsoft/data": "^0.0.26",
"@angular/common": "^8.2.4",
"@angular/core": "^8.2.4",
"apollo-angular-link-http": "^1.9.0",
"apollo-link": "^1.2.11",
"apollo-client": "^2.6.0",
"apollo-cache-inmemory": "^1.6.0",
"graphql-tag": "^2.10.0",
"graphql": "^14.5.0"
}
}
@@ -0,0 +1,274 @@
import { IDataSourceOptions, IQueryCriteria, IDataSourceTransportOptions, IDataSourceQueryAdapterOptions, IDataSourceCommandAdapterOptions, IAdvanceQueryAdapter, IFilter, IAggregate, ISort, IGroup, ISimpleFilter, ICompositeFilter, IQueryExecutionGroupResult, IQueryExecutionResult, IAggregateResult } from '@poweredsoft/data';
import { Apollo } from 'apollo-angular';
import { IGraphQLAdvanceQueryResult, IGraphQLAdvanceQueryInput, IGraphQLAdvanceQueryFilterInput, IGraphQLAdvanceQueryAggregateInput, IGraphQLAdvanceQuerySortInput, IGraphQLAdvanceQueryGroupInput, FilterType, IGraphQLAdvanceQueryAggregateResult, IGraphQLVariantResult, AggregateType } from './models';
import gql from 'graphql-tag';
import { DocumentNode } from 'graphql';
import { map, catchError } from 'rxjs/operators';
import { Observable } from 'rxjs';
export class GraphQLDataSourceOptionsBuilder<TModel, TKey> {
private _commands: { [key: string] : IDataSourceCommandAdapterOptions<any> };
constructor(private apollo: Apollo,
private queryName: string,
private queryInputName: string,
private querySelect: string,
private keyResolver: (model: TModel) => TKey,
private defaultCriteria: IQueryCriteria,
private manageNotificationMessage: boolean)
{
}
create(): IDataSourceOptions<TModel> {
let ret: IDataSourceOptions<TModel> = {
resolveIdField: this.keyResolver,
defaultCriteria: this.defaultCriteria,
manageNotificationMessage: this.manageNotificationMessage,
transport: this.createTransport()
};
return ret;
}
protected createTransport(): IDataSourceTransportOptions<TModel> {
let ret: IDataSourceTransportOptions<TModel> = {
query: this.createQuery(),
commands: this._commands
};
return ret;
}
protected createQuery(): IDataSourceQueryAdapterOptions<TModel> {
let ret: IDataSourceQueryAdapterOptions<TModel> = {
adapter: <IAdvanceQueryAdapter<IQueryCriteria, TModel>>{
handle: (query: IQueryCriteria) => {
const advanceQuery = this.createGraphQLQueryCriteria(query);
const o$ = this.apollo.query<any>({
query: this.createGraphQLQuery(query),
variables: {
criteria: advanceQuery
}
});
return o$.pipe(
map(result => {
const queryResult = result.data[this.queryName] as IGraphQLAdvanceQueryResult<TModel>;
return this.queryResultFromGraphQLAdvancedResult(query, queryResult);
}),
catchError(err => {
console.error(err);
return err;
})
);
}
}
};
return ret;
}
private queryResultFromGraphQLAdvancedResult(query: IQueryCriteria, result: IGraphQLAdvanceQueryResult<TModel>): IQueryExecutionResult<TModel> | IQueryExecutionGroupResult<TModel> {
if (query.groups && query.groups.length) {
throw 'todo';
}
const ret: IQueryExecutionResult<TModel> = {
data: result.data,
totalRecords: result.totalRecords,
numberOfPages: result.numberOfPages,
aggregates: result.aggregates ? result.aggregates.map(this.fromGraphQLAggregateResult.bind(this)) : null
};
return ret;
}
private fromGraphQLAggregateResult(agg: IGraphQLAdvanceQueryAggregateResult): IAggregateResult {
return {
path: agg.path,
type: this.normalizeFirstLetter(agg.type),
value: this.getValueFromVariantResult(agg.value)
};
}
private normalizeFirstLetter(type: string): string {
if (type) {
const ret = type.toLowerCase();
return ret.substring(0, 1).toUpperCase() + ret.substring(1);
}
return type;
}
private getValueFromVariantResult(variant: IGraphQLVariantResult): any {
if (variant && variant.typeName)
{
if (variant.typeName.toLowerCase() == "int")
return variant.intValue;
else if (variant.typeName.toLowerCase() == "long")
return variant.longValue;
else if (variant.typeName.toLowerCase() == "boolean")
return variant.booleanValue;
else if (variant.typeName.toLowerCase() == "decimal")
return variant.decimalValue;
else if (variant.typeName.toLowerCase() == "datetime")
return variant.dateTimeValue;
else if (variant.typeName.toLowerCase() == "string")
return variant.stringValue;
else if (variant.typeName.toLowerCase() == "json")
return JSON.parse(variant.json);
}
return null;
}
private createGraphQLQuery(query: IQueryCriteria): DocumentNode {
return gql`
query getAll($criteria: ${this.queryInputName}) {
${this.queryName}(params: $criteria) {
totalRecords
numberOfPages
${this.createAggregateSelect(query)}
${this.createQuerySelect(query)}
}
}
`;
}
private createAggregateSelect(query: IQueryCriteria): any {
if (query.aggregates && query.aggregates.length)
{
return `
aggregates {
type
path
value {
booleanValue
dateTimeValue
decimalValue
intValue
json
longValue
stringValue
typeName
}
}
`;
}
return '';
}
private createGraphQLQueryCriteria(query: IQueryCriteria): IGraphQLAdvanceQueryInput<TModel> {
const ret: IGraphQLAdvanceQueryInput<TModel> = {
page: query.page,
pageSize: query.pageSize,
filters: query.filters ? query.filters.map(this.convertFilter.bind(this)) : null,
sorts: query.sorts ? query.sorts.map(this.convertSort.bind(this)) : null,
aggregates: query.aggregates ? query.aggregates.map(this.convertAggregates.bind(this)) : null,
groups: query.groups ? query.groups.map(this.convertGroup.bind(this)) : null
};
return ret;
}
public addMutation<TMutation, TMutationResult>(name: string, handle: (command: TMutation) => Observable<TMutationResult>) {
this._commands[name] = <IDataSourceCommandAdapterOptions<TMutation>> {
adapter: {
handle: handle
}
};
return this;
}
private createQuerySelect(query: IQueryCriteria): string {
if (query.groups && query.groups.length) {
throw 'todo';
}
return `
data {
${this.querySelect}
}
`;
}
private convertGroup(group: IGroup): IGraphQLAdvanceQueryGroupInput {
return {
path: group.path,
ascending: group.ascending
};
}
private convertAggregates(aggregate: IAggregate): IGraphQLAdvanceQueryAggregateInput {
return {
path: aggregate.path,
type: this.resolveAggregateType(aggregate.type)
};
}
private resolveAggregateType(type: string): AggregateType {
return type ? type.toUpperCase() as any : null;
/*
if (type)
{
if (type.toUpperCase() == 'COUNT') return AggregateType.COUNT
if (type.toUpperCase() == 'SUM') return AggregateType.SUM
if (type.toUpperCase() == 'AVG') return AggregateType.AVG
if (type.toUpperCase() == 'LONGCOUNT') return AggregateType.LONGCOUNT
if (type.toUpperCase() == 'MIN') return AggregateType.MIN
if (type.toUpperCase() == 'MAX') return AggregateType.MAX
if (type.toUpperCase() == 'FIRST') return AggregateType.FIRST
if (type.toUpperCase() == 'FIRSTORDEFAULT') return AggregateType.FIRSTORDEFAULT
if (type.toUpperCase() == 'LAST') return AggregateType.LAST
if (type.toUpperCase() == 'LASTORDEFAULT') return AggregateType.LASTORDEFAULT
}
throw new Error('Aggregate type');*/
}
private convertSort(sort: ISort): IGraphQLAdvanceQuerySortInput {
return {
path: sort.path,
ascending: sort.ascending
};
}
private convertFilter(filter: IFilter): IGraphQLAdvanceQueryFilterInput {
if (filter.type == "Composite") {
const compositeFilter = filter as ICompositeFilter;
return {
not: false,
and: compositeFilter.and,
type: FilterType.COMPOSITE,
filters: compositeFilter.filters.map(this.convertFilter.bind(this)),
};
}
const simpleFilter = filter as ISimpleFilter;
return {
filters: null,
and: filter.and,
not: false,
path: simpleFilter.path,
type: this.resolveFilterType(simpleFilter.type),
value: {
stringValue: simpleFilter.value as string
}
};
}
private resolveFilterType(type: string): FilterType {
return type ? type.toUpperCase() as any: null;
/*
if (type)
{
if (type.toUpperCase() == 'EQUAL') return FilterType.EQUAL
if (type.toUpperCase() == 'CONTAINS') return FilterType.CONTAINS
if (type.toUpperCase() == 'STARTSWITH') return FilterType.STARTSWITH
if (type.toUpperCase() == 'ENDSWITH') return FilterType.ENDSWITH
if (type.toUpperCase() == 'COMPOSITE') return FilterType.COMPOSITE
if (type.toUpperCase() == 'NOTEQUAL') return FilterType.NOTEQUAL
if (type.toUpperCase() == 'GREATERTHAN') return FilterType.GREATERTHAN
if (type.toUpperCase() == 'LESSTHANOREQUAL') return FilterType.LESSTHANOREQUAL
if (type.toUpperCase() == 'GREATERTHANOREQUAL') return FilterType.GREATERTHANOREQUAL
if (type.toUpperCase() == 'LESSTHAN') return FilterType.LESSTHAN
if (type.toUpperCase() == 'IN') return FilterType.IN
if (type.toUpperCase() == 'NOTIN') return FilterType.NOTIN
}
throw new Error('unknown filter type');*/
}
}
@@ -0,0 +1,34 @@
import { Injectable } from '@angular/core';
import { IQueryCriteria, IDataSource } from '@poweredsoft/data';
import { Apollo } from 'apollo-angular';
import { GraphQLDataSourceOptionsBuilder } from './GraphQLDataSourceOptionsBuilder';
@Injectable({
providedIn: 'root'
})
export class GraphQLDataSourceService
{
constructor(private apollo: Apollo) {
}
createDataSourceOptionsBuilder<TModel, TKey>(
queryName: string,
queryInputName: string,
querySelect: string,
keyResolver: (model: TModel) => TKey,
defaultCriteria: IQueryCriteria,
manageNotificationMessage: boolean = true) : GraphQLDataSourceOptionsBuilder<TModel, TKey>
{
return new GraphQLDataSourceOptionsBuilder(
this.apollo,
queryName,
queryInputName,
querySelect,
keyResolver,
defaultCriteria,
manageNotificationMessage
);
}
}
@@ -0,0 +1,94 @@
export enum AggregateType {
COUNT,
SUM,
AVG,
LONGCOUNT,
MIN,
MAX,
FIRST,
FIRSTORDEFAULT,
LAST,
LASTORDEFAULT
}
export enum FilterType {
EQUAL,
CONTAINS,
STARTSWITH,
ENDSWITH,
COMPOSITE,
NOTEQUAL,
GREATERTHAN,
LESSTHANOREQUAL,
GREATERTHANOREQUAL,
LESSTHAN,
IN,
NOTIN
}
export interface IGraphQLVariantInput {
dateTimeValue?: Date
decimalValue?: number
intValue?: number
longValue?: number
stringValue?: string
booleanValue?: boolean;
}
export interface IGraphQLVariantResult {
dateTimeValue?: string;
decimalValue?: number;
intValue?: number;
json?: string;
longValue?: number;
stringValue?: string;
booleanValue?: boolean;
typeName: string;
}
export interface IGraphQLAdvanceQueryAggregateInput {
path?: string;
type: AggregateType;
}
export interface IGraphQLAdvanceQueryAggregateResult {
path: string
type: string
value: IGraphQLVariantResult
}
export interface IGraphQLAdvanceQueryFilterInput {
and?: boolean
filters?: IGraphQLAdvanceQueryFilterInput[]
not?: boolean
path?: string
type: FilterType
value?: IGraphQLVariantInput
}
export interface IGraphQLAdvanceQueryGroupInput {
ascending?: boolean
path: string
}
export interface IGraphQLAdvanceQuerySortInput {
ascending?: boolean
path: string
}
export interface IGraphQLAdvanceQueryInput<T> {
aggregates?: IGraphQLAdvanceQueryAggregateInput[]
filters?: IGraphQLAdvanceQueryFilterInput[]
groups?: IGraphQLAdvanceQueryGroupInput[]
page?: number
pageSize?: number
sorts?: IGraphQLAdvanceQuerySortInput[]
}
export interface IGraphQLAdvanceQueryResult<T> {
aggregates?: IGraphQLAdvanceQueryAggregateResult[];
data?: T[];
groups?: IGraphQLAdvanceQueryResult<T>[];
numberOfPages?: number;
totalRecords: number;
}
@@ -0,0 +1,9 @@
import { GraphQLDataSourceService } from "./lib/graphql-datas-source.service";
/*
* Public API Surface of ngx-data-apollo
*/
export * from './lib/graphql-datas-source.service';
export * from './lib/GraphQLDataSourceOptionsBuilder';
export * from './lib/models';
@@ -0,0 +1,26 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "../../../out-tsc/lib",
"target": "es2015",
"declaration": true,
"inlineSources": true,
"types": [],
"lib": [
"dom",
"es2018"
]
},
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"enableResourceInlining": true
},
"exclude": [
"src/test.ts",
"**/*.spec.ts"
]
}
@@ -0,0 +1,17 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "../../../out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"src/test.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}
@@ -0,0 +1,17 @@
{
"extends": "../../../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"lib",
"camelCase"
],
"component-selector": [
true,
"element",
"lib",
"kebab-case"
]
}
}
+1 -7
View File
@@ -5,12 +5,6 @@
"@angular/common": "^8.2.4",
"@angular/core": "^8.2.4",
"@poweredsoft/data": "^0.0.26",
"rxjs": "^6.5.3",
"apollo-angular-link-http": "^1.9.0",
"apollo-link": "^1.2.11",
"apollo-client": "^2.6.0",
"apollo-cache-inmemory": "^1.6.0",
"graphql-tag": "^2.10.0",
"graphql": "^14.5.0"
"rxjs": "^6.5.3"
}
}