I've done a mapping before, but not this deeply nested. I am trying to re-populate data from a corrupt db. I have manually reconstructed an orders array. I'm trying to look up data for each player, and then update the fields (which start out null) for each player:
Example: I start with data like this:
const orders = [
{
"paymentID": "ch_456",
"paymentStatus": "PAID",
"user": "kingkong#gmail.com",
"cart": {
"username": "kingkong#gmail.com",
"totalQty": 1,
"totalPrice": 80,
"items": [{
"event": "Men's BB",
"division": "Men's",
"level": "BB",
"group": "nonpro",
"field": "PAL",
"day": "Saturday",
"numplayers": 2,
"price": 80,
"players": [{
"avp_id": 1042641,
"first": "King",
"last": "Kong",
"waivers": [],
"completed": true,
"country": "USA",
"signed": false},
{
"avp_id": 1086117,
"first": "Jacob",
"last": "Ladder",
"waivers": [],
"completed": true,
"country": "USA",
"signed": false,
"shirt_size": "N/A"}],
"net": null,
"team": null,
"notes": null,
"paymentNote": null,
"waiversSent": false,
"active": true,
"paymentID": "ch_456",
"users": ["kingkong#gmail.com"],
"paymentStatus": "PAID", "__v": 4}]},
"__v": 0
},{
"paymentID": "ch_123",
"paymentStatus": "PAID",
"user": "marymac#aol.com",
"cart": {
"username": "marymac#aol.com",
"totalQty": 1,
"totalPrice": 50,
"items": [{
"event": "Junior Boys 16s",
"division": "Junior Boys",
"level": "16s",
"group": "nonpro",
"field": "Main",
"day": "Friday",
"numplayers": 2,
"price": 80,
"players": [{
"avp_id": 1022228,
"first": "Some",
"last": "Kid",
"waivers": [],
"completed": true,
"country": "USA",
"signed": false
}, {
"avp_id": 1020142,
"first": "Justin",
"last": "Kid",
"waivers": [],
"completed": true,
"country": "USA",
"signed": false,
"shirt_size": "N/A"
}
],
"net": null,
"team": null,
"notes": null,
"paymentNote": null,
"waiversSent": false,
"active": true,
"paymentID": "ch_123",
"users": ["marymac#aol.com"],
"paymentStatus": "PAID", "__v": 4
}
]
},
"__v": 0
}];
Here is my code, which I'd like to get the data from an API, and update player info to pass into a function further down:
async getLostData() {
// get the lost orders
console.log('start lost data import');
// this.adminService.GetLostOrders().subscribe(orders => {
// console.log('load each order into system', orders);
orders.forEach(order => {
order.cart.items.map(item => {
const players = item.players.map(async player => {
player = await
this.adminService.adminAVPReg(player.last, player.avp_id)
.toPromise();
console.log("updated player outside subscribe", player);
});
item.players = players;
console.log("item", item);
});
// load order with updated info, create registration, and skip pmt
// this.adminService.LoadLostOrders(order).subscribe(data => {
// console.log(data);
// console.log('finished');
// });
});
console.log("orderlist", orders);
// });}
The data I'm getting logged is interesting. What comes back first from the logger is each item, followed by orderlist, and then the updated player info. Each item shows the players array listed as ZoneAwarePromise. I have no idea how to replace that with the actual data, but I can see it's not being logged in the order I expected.
How can I get the item to return with the updated data?
From what I understood you are trying to do, I came up with this,
this.adminService.GetLostOrders().pipe(
mergeMap((orders: any[]) => from(orders).pipe(
mergeMap((order) => from(order.cart.items)),
mergeMap((item) => of(item).pipe(
mergeMap(_ => from(item.players)),
mergeMap(player => this.adminService.adminAVPReg(player.last, player.avp_id).pipe(
map(newPlayer => { player = newPlayer; return player; }))
),
toArray(),
tap(newPlayerArray => item.players = newPlayerArray)
)),
toArray(),
mergeMap(_ => this.adminService.LoadLostOrders(orders))
))
).subscribe();
OP's Edit
I implemented what you shared above, and turned it into this:
getLostData() {
// get the lost orders
console.log('start lost data import');
// get manually created orders from lostdata collection
this.adminService.GetLostOrders()
.pipe(
mergeMap((orders: any) => from(orders).pipe(
mergeMap((order: any) => from(order.cart.items)),
mergeMap((item: any) => of(item).pipe(
mergeMap(_ => from(item.players)),
mergeMap((player: any) => this.adminService.adminAVPReg(player.last, player.avp_id).pipe(
map((newPlayer: any) => {
player.avp_id = player.avp_id;
player.signed = player.signed;
player.waivers = player.waivers;
player.country = player.country;
player.completed = true;
player.sandbagger = false;
player.first = newPlayer.first;
player.last = newPlayer.last;
player.email = newPlayer.email;
player.address = newPlayer.address;
player.city = newPlayer.city;
player.state = newPlayer.state;
player.zip = newPlayer.zip;
player.shirt_size = newPlayer.shirt_size;
player.ranking = newPlayer.ranking;
player.overallRanking = newPlayer.overallRanking;
player.notes = player.notes;
player.phone = newPlayer.phone;
player.adult = newPlayer.adult;
return player; }))
),
toArray(),
tap(newPlayerArray => item.players = newPlayerArray)
)),
toArray(),
tap(_ => { this.loadlostOrders(orders);
})
))
)
.subscribe();
}
loadlostOrders(orders) {
orders.forEach(order => {
this.adminService.LoadLostOrders(order).subscribe((data) => {
console.log("success", JSON.stringify(data));
}, (error) => {
console.log("error", JSON.stringify(error));
});
});
}
Related
I have a query:
SELECT c.mainColour,t AS colour
FROM c
JOIN t IN c.creatorStyleMainColours
WHERE c.creatorDefaultStyleProfile = "test"
and it returns whole of the array inside the new colour object:
[
{
"colour": {
"mainColour": "black",
"colourPairings": [
"orange",
"silver",
"gold"
]
}
}
]
I need it to just return the main colour values
how do I just select the value of the "mainColour" so its a simple array like ["black","beige","white"] from the document below
I have tried:
SELECT VALUE c.mainColour,t AS colour
FROM c
JOIN t IN c.creatorStyleMainColours
WHERE c.creatorDefaultStyleProfile = "test"
but that returns a syntax error.
Here is the full document:
{
"accountId": "59951c4d-1f0b-483b-a020",
"creatorDefaultStyleProfile": "test",
"creatorDefaultStyleGender": "Female",
"creatorStyleAccountName": "",
"creatorStyleCategory": [
{
"categoryCode": "fashion",
"categoryName": "Fashion",
"categoryMetadata": {
"occasions": [
{
"occasionCode": "casual",
"occasionName": "Casual",
"occasionTypes": [
{
"occasionCode": "out",
"occasionName": "Everyday Wear"
}
]
}
],
"season": [
{
"seasonCode": "spring",
"seasonName": "Spring"
}
]
},
"id": "fashion"
}
],
"creatorStyleDescription": "",
"creatorStyleId": "Classic_Default",
"creatorStyleImages": [
{
"styleImageUrl": "https://4965fa50-6caf-11ed-8082e.png",
"styleImageCategory": "fullsize",
"styleImageResolution": {
"width": 269.25,
"height": 359
},
"styleImagePins": [
{
"itemId": "F243906F37487C78D7EB99880142B370",
"vector": {
"x": 198.125,
"y": 44.33332824707031
}
},
{
"itemId": "9B543E0DC1B05F6E9AFD0A88285AEEF9",
"vector": {
"x": 52.791656494140625,
"y": 46.33332824707031
}
},
{
"itemId": "3E6464FC1F12E3C6E435F751438F1468",
"vector": {
"x": 120.45832824707031,
"y": 320.3333282470703
}
},
{
"itemId": "1CD6065A4C7A0BD66E44DC8A62448534",
"vector": {
"x": 115.45832824707031,
"y": 192
}
}
]
}
],
"creatorStyleItems": [
{
"creatorStyleItemId": "9B543E0DC1B05F6E9AFD0A88285AEEF9",
"ItemType": "Chest",
"creatorStyleItemName": "t-shirt",
"creatorStyleItemImages": [
{
"imageUrl": "https://images/23660493-1-white?$XXL$",
"imageCategory": "thumbnail"
}
]
},
{
"creatorStyleItemId": "F243906F37487C78D7EB99880142B370",
"ItemType": "Chest",
"creatorStyleItemName": "chunky knit cardigan",
"creatorStyleItemImages": [
{
"imageUrl": "https://images/14399002-1-black?$XXL$",
"imageCategory": "thumbnail"
}
]
},
{
"creatorStyleItemId": "1CD6065A4C7A0BD66E44DC8A62448534",
"ItemType": "Leg",
"creatorStyleItemName": " mom jeans",
"creatorStyleItemImages": [
{
"imageUrl": "https://images-blue/202501450-1-denimblack?$XXL$",
"imageCategory": "thumbnail"
}
]
},
{
"creatorStyleItemId": "3E6464FC1F12E3C6E435F751438F1468",
"ItemType": "Feet",
"creatorStyleItemName": "trainers",
"creatorStyleItemImages": [
{
"imageUrl": "https://images./203112454-1-brown?$XXL$",
"imageCategory": "thumbnail"
}
]
}
],
"creatorStyleMainColours": [
{
"mainColour": "black",
"colourPairings": [
"beige",
"grey",
"white"
]
},
{
"mainColour": "beige",
"colourPairings": [
"black",
"grey",
"white"
]
},
{
"mainColour": "white",
"colourPairings": [
"beige",
"grey",
"black"
]
}
],
"creatorStyleMerchantGroup": "test1",
"creatorStyleName": "",
"creatorStyleProfiles": [
{
"id": "",
"profileAccountId": "test1",
"profileId": "test1",
"profileIsDefault": false,
"profileName": "classic",
"profileBiometric": {
"biometricName": "",
"biometricGender": "Female",
"biometricHeight": [
],
"biometricAgeRange": [
],
"biometricHairColour": [
],
"biometricSkinColour": [
],
"biometricBodyShape": [
],
"biometricMeasurement": {
}
},
"profilePersona": {
"personaName": "",
"personaDressSense": [
],
"personaInterests": [
],
"personaStyleIcons": [
],
"personaColours": [
]
}
}
],
"creatorStyleStatus": {
"styleStatusId": "nonpublished",
"styleStatusDescription": ""
},
"id": "classicStyle1",
"_rid": "IW43AJ08x+8BAAAAAAAAAA==",
"_self": "dbs/IW43AA==/colls/IW43AJ08x+8=/docs/IW43AJ08x+8BAAAAAAAAAA==/",
"_etag": "\"97005ae1-0000-1500-0000-638523be0000\"",
"_attachments": "attachments/",
"_ts": 1669669822
}
Elastic search extraction query is returning expected results in hints section of output but aggregation on field returning empty response
output without aggregation
{
"_shards": {
"total": 45,
"failed": 0,
"successful": 45,
"skipped": 0
},
"hits": {
"hits": [
{
"_index": "logstash-wander-2022.08.17",
"_type": "fluentd",
"_source": {
"outboundResponseStatus": "SERVICE_UNAVAILABLE"
},
"_id": "Y2NlNjkzZmEtNjZlMi00NWY4LTllNWUtOWZmNWRhMjRkMzA3",
"sort": [
1660695790244
],
"_score": null
},
{
"_index": "logstash-wander-2022.08.17",
"_type": "fluentd",
"_source": {
"outboundResponseStatus": "CONFLICT"
},
"_id": "OWNmZTFiOWEtYWQ2Mi00OGViLWFmY2EtMGQ4ZDg1NzRiYWNk",
"sort": [
1660695781810
],
"_score": null
}
],
"total": 25,
"max_score": null
},
"took": 506,
"timed_out": false
}
But adding below aggregation along with query returning empty response
"aggregations": {
"outboundResponseStatus": {
"significant_terms": {
"field": "outboundResponseStatus",
"keyed": true
}
}
}
Below is the query
{
"size": 500,
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "search string",
"default_field": "*",
"fields": [],
"type": "best_fields",
"default_operator": "or",
"max_determinized_states": 10000,
"enable_position_increments": true,
"fuzziness": "AUTO",
"fuzzy_prefix_length": 0,
"fuzzy_max_expansions": 50,
"phrase_slop": 0,
"analyze_wildcard": true,
"escape": false,
"auto_generate_synonyms_phrase_query": true,
"fuzzy_transpositions": true,
"boost": 1
}
},
{
"match_phrase": {
"message": {
"query": "search string",
"slop": 0,
"zero_terms_query": "NONE",
"boost": 1
}
}
},
{
"range": {
"#timestamp": {
"from": "now-10m",
"to": "now",
"include_lower": true,
"include_upper": true,
"format": "epoch_millis",
"boost": 1
}
}
}
],
"adjust_pure_negative": true,
"boost": 1
}
},
"version": true,
"_source": {
"includes": [
"outboundResponseStatus",
"outboundUri",
"message"
],
"excludes": []
},
"stored_fields": "*",
"script_fields": {},
"sort": [
{
"#timestamp": {
"order": "desc",
"unmapped_type": "boolean"
}
}
]
}
How to get aggregations based on field in hints results?
I'm trying to generate flate type script class using nswag
I belive there's a proprty 'flattenInheritanceHierarchy' that can do what i need. but seems like its not working. not sure what i'm missing.
I have a c# class called Result which is inheriting from Result
public partial record Result
{
public bool IsSucceeded { get; set; }
public string Message { get; set; } = string.Empty;
}
public partial record Result<T> : Result where T : new()
{
public T Value { get; set; } = new T();
}
i'm using it to retunr the result like this
public async Task<IActionResult> Create(CarDto dto)
{
return Ok(new Result<CarDto>());
}
when i generate typescript classes, actual result is
export class Result {
isSucceeded!: boolean;
message!: string;
}
export class ResultOfCarDto extends Result {
value!: CarDto;
}
but i want it like
export class ResultOfCarDto {
isSucceeded!: boolean;
message!: string;
value!: CarDto;
}
here's my nswag.json
{
"runtime": "Net60",
"defaultVariables": null,
"documentGenerator": {
"aspNetCoreToOpenApi": {
"project": "Web.csproj",
"msBuildProjectExtensionsPath": null,
"configuration": null,
"runtime": null,
"targetFramework": null,
"noBuild": true,
"verbose": false,
"workingDirectory": null,
"requireParametersWithoutDefault": true,
"apiGroupNames": null,
"defaultPropertyNameHandling": "CamelCase",
"defaultReferenceTypeNullHandling": "Null",
"defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "Integer",
"flattenInheritanceHierarchy": true,
"generateKnownTypes": true,
"generateEnumMappingDescription": true,
"generateXmlObjects": false,
"generateAbstractProperties": false,
"generateAbstractSchemas": true,
"ignoreObsoleteProperties": true,
"allowReferencesWithProperties": false,
"excludedTypeNames": [],
"serviceHost": null,
"serviceBasePath": null,
"serviceSchemes": [],
"infoTitle": "API",
"infoDescription": null,
"infoVersion": "1.0.0",
"documentTemplate": null,
"documentProcessorTypes": [],
"operationProcessorTypes": [],
"typeNameGeneratorType": null,
"schemaNameGeneratorType": null,
"contractResolverType": null,
"serializerSettingsType": null,
"useDocumentProvider": true,
"documentName": "v1",
"aspNetCoreEnvironment": null,
"createWebHostBuilderMethod": null,
"startupType": null,
"allowNullableBodyParameters": false,
"output": "wwwroot/api/specification.json",
"outputType": "OpenApi3",
"assemblyPaths": [],
"assemblyConfig": null,
"referencePaths": [],
"useNuGetCache": false
}
},
"codeGenerators": {
"openApiToTypeScriptClient": {
"className": "{controller}Client",
"moduleName": "",
"namespace": "",
"typeScriptVersion": 4.3,
"template": "Angular",
"promiseType": "Promise",
"httpClass": "HttpClient",
"withCredentials": false,
"useSingletonProvider": true,
"injectionTokenType": "InjectionToken",
"rxJsVersion": 6.0,
"dateTimeType": "Date",
"nullValue": "Undefined",
"generateClientClasses": false,
"generateClientInterfaces": false,
"generateOptionalParameters": false,
"exportTypes": true,
"wrapDtoExceptions": false,
"exceptionClass": "SwaggerException",
"clientBaseClass": null,
"wrapResponses": false,
"wrapResponseMethods": [],
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"protectedMethods": [],
"configurationClass": null,
"useTransformOptionsMethod": false,
"useTransformResultMethod": false,
"flattenInheritanceHierarchy": false,
"generateDtoTypes": true,
"operationGenerationMode": "MultipleClientsFromOperationId",
"markOptionalProperties": false,
"generateCloneMethod": false,
"typeStyle": "Class",
"enumStyle": "Enum",
"useLeafType": true,
"classTypes": [],
"extendedClasses": [],
"extensionCode": null,
"generateDefaultValues": true,
"generateAbstractProperties": false,
"generateAbstractSchemas": false,
"ignoreObsoleteProperties": true,
"excludedTypeNames": [],
"excludedParameterNames": [],
"includeHttpContext": false,
"handleReferences": false,
"generateTypeCheckFunctions": false,
"generateConstructorInterface": false,
"convertConstructorInterfaceData": false,
"importRequiredTypes": true,
"useGetBaseUrlMethod": false,
"baseUrlTokenName": "API_BASE_URL",
"queryNullValue": "",
"inlineNamedDictionaries": false,
"inlineNamedAny": false,
"templateDirectory": null,
"typeNameGeneratorType": null,
"propertyNameGeneratorType": null,
"enumNameGeneratorType": null,
"serviceHost": null,
"serviceSchemes": null,
"output": "ClientApp/src/app/dto/api-dtos.ts"
}
}
}
addtionally its generating 3 fromJS, init and toJSON functions which i also dont want
export class StatusCountDto {
count!: number;
status!: string;
#region I dont want to generate this
init(_data?: any) {
if (_data) {
this.count = _data["count"];
this.status = _data["status"];
}
}
static fromJS(data: any): IssueCountDto {
data = typeof data === 'object' ? data : {};
let result = new IssueCountDto();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["count"] = this.count;
data["status"] = this.status;
return data;
}
#endregion I dont want to generate this
}
any suggesstion?
I have a taxonomy with an ACF repeater field. I am trying to add rows in a callback for a custom REST API endpoint and having no luck. The scheme for the field is:
{
"key": "field_5faa2bc09fe7b",
"label": "team",
"name": "team",
"type": "repeater",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"collapsed": "",
"min": 0,
"max": 10,
"layout": "table",
"button_label": "",
"sub_fields": [
{
"key": "field_5faa2bce9fe7c",
"label": "Role",
"name": "role",
"type": "post_object",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"post_type": [
"role"
],
"taxonomy": "",
"allow_null": 0,
"multiple": 0,
"return_format": "id",
"ui": 1
},
{
"key": "field_5faa2c0b9fe7d",
"label": "User",
"name": "user",
"type": "user",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"role": "",
"allow_null": 0,
"multiple": 0,
"return_format": "id"
}
]
}
I use the following to add a row to the field - and having no luck:
function wp_api_assign_internal_writer() {
register_rest_route( 'mynamespace/v1', 'assign_internal_writer/', array(
'methods' => 'POST',
'callback' => 'assign_internal_writer_callback',
));
}
function assign_internal_writer_callback( $request ) {
$parameters = $request->get_params();
$task = $parameters['task'];
$user = $parameters['user'];
$project_set = $parameters['project_set'];
if($task != '' && $user != '' && $project_set != '' ){
$row = array(
'field_5faa2bce9fe7c' => '268',
'field_5faa2c0b9fe7d' => $user
);
add_row('team', $row, $project_set);
return get_term_meta($project_set);
}else{
return 'Please supply the correct request parameters, Task ID and User ID';
}
}
Any idea what I am doing wrong? Does add row work only for Post and not Term....? I doubt thats it...
Based on your ACF field type i can only suggest to check if it actually expect the real object for the Wp_Post and for the Wp_User. Maybe try to convert your id's into objects and see if it works.
If that's not the issue please be more clear about what you mean with "had no luck". Does that mean you have fatal errors? no warning? no row inserted? ecc...
I have array like below as one of the properties for my object. I'd like to extract certain fields and return it still as array in output. For example I want only name and storageAccountType to be returned like below
Desired Output
[
{
"name": "Data",
"storageAccountType": "Standard_LRS"
},
{
"name": "Disk2",
"storageAccountType": "Standard_LRS"
}
]
Input Array
[
{
"name": "Data",
"createOption": "Attach",
"diskSizeGB": 10,
"managedDisk": {
"id": "/subscriptions/24ba3e4c-45e3-4d55-8132-6731cf25547f/resourceGroups/GREG/providers/Microsoft.Compute/disks/Data",
"storageAccountType": "Standard_LRS"
},
"caching": "None",
"toBeDetached": false,
"lun": 0
},
{
"name": "Disk2",
"createOption": "Attach",
"diskSizeGB": 10,
"managedDisk": {
"id": "/subscriptions/24ba3e4c-45e3-4d55-8132-6731cf25547f/resourceGroups/GREG/providers/Microsoft.Compute/disks/Disk2",
"storageAccountType": "Standard_LRS"
},
"caching": "None",
"toBeDetached": false,
"lun": 1
}
]
here's a direction you could follow (which assumes you actually needs to get back arrays and not to have each element in the array in its own row. if the latter is good, remove the rows with the comments (// *)
datatable(some_value:string, d:dynamic) // just a sample data set with 2 records
[
"hello", dynamic([
{
"name": "Data",
"createOption": "Attach",
"diskSizeGB": 10,
"managedDisk": {
"id": "/subscriptions/24ba3e4c-45e3-4d55-8132-6731cf25547f/resourceGroups/GREG/providers/Microsoft.Compute/disks/Data",
"storageAccountType": "Standard_LRS"
},
"caching": "None",
"toBeDetached": false,
"lun": 0
},
{
"name": "Disk2",
"createOption": "Attach",
"diskSizeGB": 10,
"managedDisk": {
"id": "/subscriptions/24ba3e4c-45e3-4d55-8132-6731cf25547f/resourceGroups/GREG/providers/Microsoft.Compute/disks/Disk2",
"storageAccountType": "Standard_LRS"
},
"caching": "None",
"toBeDetached": false,
"lun": 1
}
]), "world", dynamic([
{
"name": "Data3",
"createOption": "Attach",
"diskSizeGB": 10,
"managedDisk": {
"id": "/subscriptions/24ba3e4c-45e3-4d55-8132-6731cf25547f/resourceGroups/GREG/providers/Microsoft.Compute/disks/Data",
"storageAccountType": "Standard_LRS"
},
"caching": "None",
"toBeDetached": false,
"lun": 0
},
{
"name": "Disk23",
"createOption": "Attach",
"diskSizeGB": 10,
"managedDisk": {
"id": "/subscriptions/24ba3e4c-45e3-4d55-8132-6731cf25547f/resourceGroups/GREG/providers/Microsoft.Compute/disks/Disk2",
"storageAccountType": "Standard_LRS"
},
"caching": "None",
"toBeDetached": false,
"lun": 1
}
])
]
// --> answer starts here <--
| extend r = rand() // *
| mv-apply d on (
project d = pack("name", d.name, "storageAccountType", d.managedDisk.storageAccountType)
)
| summarize d = make_list(d) by r, some_value // *
| project-away r // *