-
Notifications
You must be signed in to change notification settings - Fork 9
/
PagedContentItemsQuery.cs
291 lines (271 loc) · 11.6 KB
/
PagedContentItemsQuery.cs
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
using EasyOC.Core.Indexes;
using EasyOC.DynamicTypeIndex;
using EasyOC.DynamicTypeIndex.Models;
using EasyOC.DynamicTypeIndex.Service;
using EasyOC.GraphQL.Queries.Types;
using FreeSql.Internal.CommonProvider;
using FreeSql.Internal.Model;
using GraphQL;
using GraphQL.Types;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OrchardCore.Apis.GraphQL;
using OrchardCore.Apis.GraphQL.Resolvers;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.ContentManagement.Records;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MSHttp = Microsoft.AspNetCore.Http;
namespace EasyOC.GraphQL.Queries
{
public class PagedContentItemsQuery : ISchemaBuilder
{
private readonly MSHttp.IHttpContextAccessor _httpContextAccessor;
private readonly IStringLocalizer S;
private readonly IFreeSql _freesql;
public PagedContentItemsQuery(MSHttp.IHttpContextAccessor httpContextAccessor,
IStringLocalizer<ContentItemByVersionQuery> localizer, IFreeSql freesql
)
{
_httpContextAccessor = httpContextAccessor;
S = localizer;
_freesql = freesql;
}
public Task<string> GetIdentifierAsync() => Task.FromResult(string.Empty);
const string dynamicfilterDescription = "The dynamic filter: see:http://www.freesql.net/guide/select.html#%E7%89%B9%E5%88%AB%E4%BB%8B%E7%BB%8D-wheredynamicfilter";
public Task BuildAsync(ISchema schema)
{
var typeType = new PagedContentItemsType();
var field = new FieldType()
{
Name = "PagedContentItems",
Description = S["Content items are instances of content types, just like objects are instances of classes."],
Resolver = new LockedAsyncFieldResolver<PagedContentItemResult>(ResolveAsync),
Type = typeType.GetType(),
ResolvedType = typeType,
Arguments = new QueryArguments(
new QueryArgument<IntGraphType>
{
Name = "page", Description = "The page number", DefaultValue = 1
},
new QueryArgument<BooleanGraphType>
{
Name = "published", Description = "The published status filter", DefaultValue = true
},
new QueryArgument<BooleanGraphType>
{
Name = "latest", Description = "The latest version status filter", DefaultValue = true
},
new QueryArgument<IntGraphType>()
{
Name = "pageSize", Description = "The page size", DefaultValue = 10
},
new QueryArgument<DynamicFilterInput>()
{
Name = "dynamicFilter", Description = dynamicfilterDescription
},
new QueryArgument<StringGraphType>()
{
Name = "dynamicJSONFilter", Description = dynamicfilterDescription, DefaultValue = ""
},
new QueryArgument<DynamicOrderByInput>()
{
Name = "orderBy", Description = "The order by info."
}, GetContentTypePickerArgument()
)
};
schema.Query.AddField(field);
schema.RegisterType<DynamicFilterInput>();
return Task.CompletedTask;
// schema.RegisterType<DynamicOrderByInput>();
}
private async Task<PagedContentItemResult> ResolveAsync(IResolveFieldContext context)
{
var contentType = context.GetArgument<string>("contentType");
if (string.IsNullOrEmpty(contentType))
{
return null;
}
var published = context.GetArgument<bool?>("published") ?? true;
var latest = context.GetArgument<bool?>("latest") ?? true;
var serviceProvider = context.RequestServices;
var dynamicIndexAppService = serviceProvider.GetRequiredService<IDynamicIndexAppService>();
var dIndexConfig = await dynamicIndexAppService.GetDynamicIndexConfigAsync(contentType);
var prepareQuery = _freesql.Select<ContentItemIndex, DIndexBase>()
.LeftJoin((a, b) => a.ContentItemId == b.ContentItemId && a.ContentItemVersionId == b.ContentItemVersionId)
.Where((a, b) =>
a.ContentType == contentType &&
a.Published == published &&
a.Latest == latest
);
if (dIndexConfig != null)
{
var indexType = await dynamicIndexAppService.GetDynamicIndexTypeAsync(dIndexConfig.EntityInfo);
var joinType = (prepareQuery as Select0Provider)?._tables.LastOrDefault();
if (joinType != null)
{
joinType.Table = _freesql.CodeFirst.GetTableByEntity(indexType);
}
}
DynamicFilterInfo filterInfo = null;
if (context.HasPopulatedArgument("dynamicJSONFilter"))
{
var filterStr = context.GetArgument<string>("dynamicJSONFilter");
filterInfo = JsonConvert.DeserializeObject<DynamicFilterInfo>(filterStr);
}
else if (context.HasPopulatedArgument("dynamicFilter"))
{
filterInfo = context.GetArgument<DynamicFilterInfo>("dynamicFilter");
}
if (filterInfo is not null)
{
if (dIndexConfig != null)
{
filterInfo = ReplaceFieldName(filterInfo, dIndexConfig);
}
prepareQuery = prepareQuery.WhereDynamicFilter(filterInfo);
}
//如果 排序不为空
if (context.HasPopulatedArgument("orderBy"))
{
var orderByArguments = JObject.FromObject(context.Arguments["orderBy"].Value);
if (orderByArguments != null&& orderByArguments.ContainsKey("field"))
{
var orderByField = orderByArguments["field"].Value<string>();
var orderByDirection = orderByArguments["direction"].Value<string>();
if (dIndexConfig != null)
{
orderByField = FieldNameToDbColumnName(orderByField, dIndexConfig);
}
if (orderByField != null && orderByDirection != null)
{
prepareQuery = prepareQuery.OrderByPropertyName(orderByField, orderByDirection != "1");
}
}
}
var page = context.GetArgument<int?>("page") ?? 1;
var pageSize = context.GetArgument<int?>("pageSize") ?? 10;
var ids = await prepareQuery
.Count(out var totalCount)
.Page(page, pageSize)
.ToListAsync((x, b) => x.ContentItemId);
if (ids != null && !ids.Any())
{
return null;
}
var contentManager = serviceProvider.GetService<IContentManager>();
var contentItem = await contentManager?.GetAsync(ids, latest)!;
var queryResults = new PagedContentItemResult
{
Items = contentItem ?? new List<ContentItem>(), Total = Convert.ToInt32(totalCount)
};
return queryResults;
}
private QueryArgument GetContentTypePickerArgument()
{
var definitionManager = _httpContextAccessor.HttpContext.RequestServices.GetRequiredService<IContentDefinitionManager>();
var pickerType = new EnumerationGraphType()
{
Name = "ContentTypePicker",
};
var contentTypes = definitionManager.LoadTypeDefinitions()
.Select(x =>
{
var stereotype = x.Settings.ToObject<ContentTypeSettings>()?.Stereotype;
return new
{
x.DisplayName, x.Name, Stereotype = stereotype
};
}
)
.OrderBy(x => x.Stereotype);
foreach (var typeDef in contentTypes)
{
pickerType.AddValue(typeDef.Name, typeDef.DisplayName, typeDef.Name, deprecationReason: typeDef.Stereotype);
}
return new QueryArgument<NonNullGraphType<EnumerationGraphType>>()
{
Name = "contentType", Description = "picker content type", ResolvedType = new NonNullGraphType(pickerType)
};
}
private string FieldNameToDbColumnName(string name, DynamicIndexConfigModel dIndexConfig)
{
try
{
var colConfig = dIndexConfig.Fields
.Where(x => x.ContentFieldOption != null)
.FirstOrDefault(
x =>
{
if (x.ContentFieldOption.FieldName.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (x.ContentFieldOption.FieldType is "ContentItemPickerField" or "UserPickerField")
{
if (name.Equals($"{x.ContentFieldOption.FieldName}.firstValue", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
});
if (colConfig is not null)
{
if (!colConfig.ContentFieldOption.IsSelfField)
{
return colConfig.GetCsFieldName();
}
}
return name;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private DynamicFilterInfo ReplaceFieldName(DynamicFilterInfo filterInfo, DynamicIndexConfigModel dIndexConfig)
{
try
{
if (filterInfo.Field is not null)
{
filterInfo.Field = FieldNameToDbColumnName(filterInfo.Field, dIndexConfig);
}
if (filterInfo.Value is string)
{
var strVal = filterInfo.Value.ToString();
strVal = (strVal ?? string.Empty).Trim();
if (strVal.StartsWith("["))
{
filterInfo.Value = JsonConvert.DeserializeObject<List<string>>(strVal);
}
// else if (strVal.StartsWith("{"))
// {
// filterInfo.Value = JsonConvert.DeserializeObject(strVal);
// }
}
if (filterInfo.Filters != null && filterInfo.Filters.Any())
{
foreach (var filterItem in filterInfo.Filters)
{
ReplaceFieldName(filterItem, dIndexConfig);
}
}
return filterInfo;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}