-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
85 lines (77 loc) · 2.49 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { ConnectionInfo, ConnectionPool, Database } from 'sqlex';
import { Database as SchemaInfo } from 'sqlex/dist/types';
import { Accessor, AccessorOptions } from './accessor';
import { GraphQLSchemaBuilder, SchemaBuilderOptions } from './schema';
import { Schema as SchemaConfig } from 'sqlex/dist/config';
import { Schema } from 'sqlex/dist/schema';
import { Maybe } from 'graphql/jsutils/Maybe';
import {
graphql,
GraphQLFieldResolver,
GraphQLTypeResolver,
printError,
} from 'graphql';
import { OperatorMap } from 'sqlex/dist/filter';
export interface ArchenConfig {
database: {
connection: ConnectionPool | ConnectionInfo;
schemaInfo?: SchemaInfo;
};
schema?: SchemaConfig;
accessor?: AccessorOptions;
graphql?: SchemaBuilderOptions;
}
export class Archen {
config: ArchenConfig;
accessor!: Accessor;
schema!: Schema;
graphql!: GraphQLSchemaBuilder;
constructor(config: ArchenConfig) {
this.config = config;
const schemaInfo = config.database.schemaInfo;
if (schemaInfo) {
this.bootstrap(schemaInfo, config.graphql.operators);
}
}
async bootstrap(schemaInfo?: SchemaInfo, operators?: OperatorMap) {
if (!schemaInfo) {
const database = new Database(this.config.database.connection, undefined, operators);
await database.buildSchema(this.config.schema);
this.schema = database.schema;
this.accessor = new Accessor(database, this.config.accessor);
} else {
this.schema = new Schema(schemaInfo, this.config.schema);
this.accessor = new Accessor(
new Database(this.config.database.connection, this.schema, operators),
this.config.accessor
);
}
this.graphql = new GraphQLSchemaBuilder(this.schema, this.config.graphql);
}
async query<T>(args: QueryArgs, dataKey?: string) {
const { data, errors } = await graphql({
schema: this.graphql.getSchema(),
rootValue: this.graphql.getRootValue(),
contextValue: this.accessor,
...args,
});
if (errors) {
const message = errors.map((error) => printError(error)).join('\n');
throw new Error(message);
}
return (dataKey ? data[dataKey] : data) as T;
}
shutdown() {
if (this.accessor) {
return this.accessor.db.end();
}
}
}
export interface QueryArgs {
source: string;
variableValues?: Maybe<{ [key: string]: any }>;
operationName?: Maybe<string>;
fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;
}
export { Accessor };