Custom Serde Deserializer for JSON with Inconsistent Field Names in Rust - rust

I'm trying to make a deserializer for the FullOrder struct from the CEX.IO exchange (https://cex.io/rest-api#/definitions/FullOrder). It unfortunately doesn't contain a consistent definition, and has fields as labelled below:
ta:{symbol2} string total amount in current currency (Maker)
tta:{symbol2} string total amount in current currency (Taker)
fa:{symbol2} string fee amount in current currency (Maker)
tfa:{symbol2} string fee amount in current currency (Taker)
a:{symbol1}:cds string credit, debit and saldo merged amount in current currency
So, for example, it could be tta:USD in one message or tta:EUR in another.
I've been following this guide (https://serde.rs/deserialize-struct.html) in creating my struct, and I've got all the way through it bar one thing - the final part requires specifying all the fields.
In the field visitor, I have the following to handle the fields in advance:
if value.starts_with("ta:") {
Ok(Field::TotalMakerAmount)
} else if value.starts_with("tta:") {
Ok(Field::TotalTakerAmount)
} else if value.starts_with("fa:") {
Ok(Field::FeeMakerAmount)
} else if value.starts_with("tfa:") {
Ok(Field::FeeTakerAmount)
} else if value.starts_with("a:") {
Ok(Field::CreditDebitSalvo)
But the deserialize_struct requires a list of all the fields to visit. Is there anyway I can get a hold of all fields dynamically to pass through here? Or have I reached the extreme of what a serde deserializer can do?
Thanks

Related

How can a table be a field type in jHipster jdl?

Tables
I'm having a problem generating these tables using JHipster jdl with mysql. I need to know if I can create a field with a table as type or if a field can have a JSON type and how. If there's any other solution feel free to contribute, Thanks in advance.
entity Note {
Min Float
Max Float
}
entity Product {
price Note
price2020 Note
price2021 Note
price2022 Note
}
Your design should be expressed as relations
entity Note {
Min Float
Max Float
}
entity Product {
}
relationship OneToOne {
Product{price} to Note
Product{price2020} to Note
Product{price2021} to Note
Product{price2022} to Note
}
However, I seriously question your design to have one column/relation per year, it's more a spreadsheet habit and it just does not scale. Each year you will have to modify your database and code.
I would rather consider adding a relation table that maps a product/year to a price.

Retrieve OptionSet from Dynamics Web API MetaData

I'm trying to retrieve the option set values (localized labels and integer Ids) for a specific field on a specific entity. Below is the code that I am using, but every time I execute it, it brings back ALL optionsets that are currently in my system (about 800+) and I don't want to do that.
EntityDefinitions(LogicalName='#MY_ENTITY#')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$filter=LogicalName eq '#MY_ENTITY_ATTRIBUTE#'&$expand=OptionSet
maybe this can help,
/api/data/v9.1/ENTITY(guid OR Filter)?$select=ATTRIBUTE1,ATTRIBUTE2
include header:
{
"Prefer": "odata.include-annotations=OData.Community.Display.V1.FormattedValue"
}
this gives us a response like this:
{
"ATTRIBUTE1#OData.Community.Display.V1.FormattedValue": "Person",
"ATTRIBUTE1": 1,
"ATTRIBUTE2#OData.Community.Display.V1.FormattedValue": "Company",
"ATTRIBUTE2": 2
}
I'm using the stringmap entity to retrieve the optionsets.
This represents the optionsets as a simple table on which you can filter in the query
For example by calling:
/stringmaps?$filter=(objecttypecode eq 'contacts')
you get only the optionsets which are use in the contact entity. You can also filter on attribute name, the option value (field value) or option id (field attributevalue).

In Core Data, how sort an NSFetchRequest depending on the sum of an attribute of a child entity? (SwiftUI)

I am building an iOS app in SwiftUI for which I have a Core Data model with two entities:
CategoryEntity with attribute: name (String)
ExpenseEntity with attributes: name (String) and amount (Double)
There is a To-many relationship between CategoryEntity and ExpenseEntity (A category can have many expenses).
I’m fetching the categories and showing them in a list together with the sum of the expenses for each category as follows: Link to app screenshot
I would like to add a sort to the fetch request so the categories appear in order depending on the total amount of their expenses. In the example of the previous picture, the order of appearance that I would like to get would be: Tech, Clothes, Food and Transport. I don’t know how to approach this problem. Any suggestions?
In my current implementation of the request, the sorted is done alphabetically:
// My current implementation for fetching the categories
func fetchCategories() {
let request = NSFetchRequest<CategoryEntity>(entityName: "CategoryEntity")
let sort = NSSortDescriptor(keyPath: \CategoryEntity.name, ascending: true)
request.sortDescriptors = [sort]
do {
fetchedCategories = try manager.context.fetch(request)
} catch let error {
print("Error fetching. \(error.localizedDescription)")
}
}
You don't have to make another FetchRequest, you can just sort in a computed property like this:
(I assume your fetched results come into a var called fetchedCategories.)
var sortedCategories: [CategoryEntity] {
return fetchedCategories.sorted(by: { cat1, cat2 in
cat1.expensesArray.reduce(0, { $0 + $1.amount }) >
cat2.expensesArray.reduce(0, { $0 + $1.amount })
})
}
So this sorts the fetchedCategories array by a comparing rule, that looks at the sum of all cat1.expenses and compares it with the sum of cat2.expenses. The >says we want the large sums first.
You put the computed var directly in the View where you use it!
And where you used fetchedCategories before in your view (e.g. a ForEach), you now use sortedCategories.
This will update in the same way as the fetched results do.
One approach would be to include a derived attribute in your CategoryEntity model description which keeps the totals for you. For example, to sum the relevant values from the amount column within an expenses relation:
That attribute should be updated whenever you save your managed object context. You'll then be able to sort it just as you would any other attribute, without the performance cost of calculating the expense sum for each category whenever you sort.
Note that this option only really works if you don't have to do any filtering on expenses; for example, if you're looking at sorting based on expenses just in 2022, but your core data store also has seconds in 2021, the derived attribute might not give you the sort order you want.

How to turn String Value into Number - Google Tag Manager

Im setting up my Google Tag Manager and I want to grab the purchase value from my Data Layer. This works fine, but Facebook doesn't recognize this value as its a "String" and not a number.
Therefore my question is: How can I convert this String (Return Type) to a Number (Return Type) in order for Facebook to pick it up? If that helps, its a currency.
Create JavaScript Variable named "String2Number Convertor"
function(){
return function(s){
return +s;
}
}
Create another JavaScript Variable named "Facebook Purchase Value"
function(){
return {{String2Number Convertor}}({{DataLayer Conversion Value}})
}
I assume you have your purchase value in data layer variable I called in this example as DataLayer Conversion Value
With this approach you can convert any other variables into number.

How do I read write a content item in a separate database transaction to that of the request

I have a Purchase Order content type in my Orchard application. Among other properties it has a PurchaseOrderNumber. The purchase order number is assigned when the user saves the purchase order for the first time. I use a custom controller and views for implementing the purchase order CRUD operations.
I have a purchase order number definition part which is attached to a company content type where the next purchase order number, a prefix and padding is saved. So when the system generates the next purchase order number, the prefix (e.g. PO) is used together with the next number (e.g. 123) and the padding (e.g. 5) to generate a string - e.g. PO00123.
When the purchase order number is generated the next purchase order number stored in the purchase order definition part attached to the company content item is incremented and saved so that when a user creates another purchase order it will be assigned the next number.
My challenge here is to prevent duplicate purchase order numbers from being assigned if two users create a new purchase order at the same time.
I was thinking of creating an ISingletonDependency that uses lock (_lock) {...} to wrap code that will generate the next number. This way multiple request can ask for the next number and always get the next unique number. How do I implement this though? I can't figure out how to get access to an IContentManager that has its own database transaction.
Or is there a different pattern that I should rather use?
I figured it out after looking at the Orchard.Tasks.Locking.Services.DistributedLockService class. You need to take a dependency on ILifetimeScope and then resolve ITransactionManager and IContentManager.
lock (_lock) {
using (var childLifetimeScope = _lifetimeScope.BeginLifetimeScope()) {
var transactionManager = childLifetimeScope.Resolve<ITransactionManager>();
var contentManager = childLifetimeScope.Resolve<IContentManager>();
try {
transactionManager.RequireNew(IsolationLevel.Serializable);
var contentItem = contentManager.GetLatest(contentItemId);
var number = CompileNewNumber(contentItem);
contentManager.Publish(contentItem);
return number;
}
catch (Exception exception) {
Logger.Error(exception, "Error compiling next number.");
transactionManager.Cancel();
return "";
}
}
}

Resources