AfterMap context.mapper.map does not call the expected map - automapper

A breakpoint in the following code in line resContext.Mapper... does stop the execution
CreateMap<MedicationFactory.Definition, TimeDescription>()
.IgnoreAllUnmapped()
.AfterMap((adapter, description, resContext) =>
{
resContext.Mapper.Map<MedicationTimePattern, TimeDescription>(adapter.TimePattern, description);
})
I assume next this map should be called, but that seems not to be the case. A breakpoint here in the line resContext.Mapper is never hit. Is there an obvious reason?
CreateMap<MedicationTimePattern, TimeDescription>()
.IgnoreAllUnmapped()
.ForMember(dst => dst.ExtendedRRules,
src =>
src.MapFrom((source, destination, member, resContext) =>
{
return resContext.Mapper.Map<ExtendedRRule[]>(source.ClassicDosage.ToRRule().ToArray());
}))
Already tried https://docs.automapper.org/en/stable/Understanding-your-mapping.html
but that did not really help.

Related

Reduce nested match statements with unwrap_or_else in Rust

I have a rust program that has multiple nested match statements as shown below.
match client.get(url).send() {
Ok(mut res) => {
match res.read_to_string(&mut s) {
Ok(m) => {
match get_auth(m) {
Ok(k) => k,
Err(_) => return Err(“a”);
}
},
Err(_) => {
return Err(“b”);
}
}
},
Err(_) => {
return Err(“c”);
},
};
All the variables k and m are of type String.I am looking for a way to make the code more readable by removing excessive nested match statements keeping the error handling intact since both the output and the error types are important for the problem.Is it possible to achieve this by unwrap_or_else?
The .map_err() utility converts a Result to have a new error type, leaving the success type alone. It accepts a closure that consumes the existing error value and returns the new one.
The ? operator will early-return the error in the Err case, and unwrap in the Ok case.
Combining these two allows you to express this same flow succinctly:
get_auth(
client.get(url).send().map_err(|_| "c")?
.read_to_string(&mut s).map_err(|_| "b")?
).map_err(|_| "a")?
(I suspect that you actually want to pass s to get_auth() but that's not what the code in your question does, so I'm choosing to represent the code you posted instead of imaginary code that I'm guessing about.)

Update prop for dynamically inserted element

New to react... Really banging my head against it with this one... I'm trying to figure out how to get a dynamically inserted component to update when the props are changed. I've assigned it to a parent state object but it doesn't seem to re-render. I've read that this is what's supposed to happen.
I was using ReactDOM.unmountComponentAtNode to re-render the specific elements I needed to, but it kept yelling at me with red text.
I need to hide "chat.message" unless the user has the authority to see it (server just sends empty string), but I still need to render the fact that it exists, and reveal it should the user get authentication. I'm using a css transition to reveal it, but I really need a good way to update the chat.message prop easily.
renderChats(uuid){
let userState = this.state.userStates.find(user => {
return user.uuid === uuid;
});
const children = userState.chats.map((chat) => {
let ChatReactElement = this.getChatMarkup(chat.cuid, chat.message, chat.status);
return ChatReactElement;
});
ReactDOM.render(children, document.getElementById(`chats-${this.state.guid}-${uuid}`));
}
getChatMarkup() just returns JSX and inserts Props... I feel like state should be getting passed along here. Even when I use a for-loop and insert the state explicitly, it doesn't seem to re-render on changes.
getChatMarkup(cuid, message, status){
return(
<BasicChatComponent
key={cuid}
cuid={cuid}
message={message}
status={status}
/>
);
}
I attempted to insert some code line this:
renderChats(uuid){
let userState = this.state.userStates.find(user => {
return user.uuid === uuid;
});
const children = userState.chats.map((chat) => {
let ChatReactElement = this.getChatMarkup(chat.cuid, chat.message, chat.status);
if(chat.status.hidden)
this.setState({ hiddenChatRE: [ ...this.state.hiddenChatRE, ChatReactElement ] }); // <== save elements
return ChatReactElement;
});
ReactDOM.render(children, document.getElementById(`chats-${this.state.guid}-${uuid}`));
}
and later in my code:
this.state.hiddenChatRE.every(ReactElement => {
if(ReactElement.key == basicChats[chatIndex].cuid){
ReactElement.props = {
... //completely invalid code
}
}
});
The only response I see here is my ReactDOM.unmountComponentAtNode(); approach...
Can anyone point me in the right direction here?
Although perhaps I should be kicking myself, I read up on how React deals with keys on their components. So there's actually a fairly trivial answer here if anyone comes looking... Just call your render function again after you update the state.
In my case, something like:
this.setState(state =>({
...state,
userStates : state.userStates.map((userstate) => {
if(userstate.uuid == basicChats[chatIndex].uuid) return {
...userstate,
chats: userstate.chats.map((chat) => {
if(chat.cuid == basicChats[chatIndex].cuid){
//
return {
cuid: basicChats[chatIndex].cuid,
message: basicChats[chatIndex].message,
status: basicChats[chatIndex].status
}
}
else return chat;
})
}
else return userstate;
})
}));
and then, elsewhere in my example:
this.state.userStates.map((userstate) => {
this.renderChats(userstate.uuid);
});
Other than the fact that I'd recommend using indexed arrays for this example to cut complexity, this is the solution, and works. This is because even though it feels like you'd end up with duplicates (that was my intuition), the uid on the BasicChatComponent itself makes all the difference, letting react know to only re-render those specific elements.

Selecting (and deleting) entire function with definition (INCLUDING whitespace) in Vim

I recently switched to using Vim (with VSCode) as my editor.
I'm trying to delete a function with it's definition in JavaScript. I looked on google and here on StackOverflow and found this question. Unfortunately the answers for this question only work for functions without white space.
Here is how my function looks:
const useBattery = () => {
const [battery, setBattery] = useState({ level: 0, charging: false });
const handleChange = ({ target: { level, charging } }) => setBattery({ level, charging });
useEffect(() => {
let battery;
navigator.getBattery().then(bat => {
battery = bat;
battery.addEventListener("levelchange", handleChange);
battery.addEventListener("chargingchange", handleChange);
handleChange({ target: battery });
});
return () => {
battery.removeEventListener("levelchange", handleChange);
battery.removeEventListener("chargingchange", handleChange);
};
}, []);
return battery;
};
I tried several approaches, the best one was da{ when my cursor is within the function. This motion will delete the function body, but not the definition.
Is there any way to delete the function and the definition in one motion using Vim, if there is white space in the function?
From inside the function, as you say da{ deletes only the braces and its content, without the preceding declaration or the following semicolon. However... if we switch to linewise...?
There is a semi-hidden section a bit under :help exclusive-linewise with bold heading but no tag to jump to: "FORCING A MOTION TO BE LINEWISE, CHARACTERWISE OR BLOCKWISE", saying that we can switch to a non-default selection by using v (characterwise), V (linewise) or Ctrl-V (blockwise) immediately after the operator. So...
dVa{
As mentioned in the post you linked to, d]] when the cursor is placed at the beginning of the function definition will delete the whole function.

Running node sqlite3 code synchronously

I'm having trouble adjusting to the async-first nature of node / js / typescript. This intent of this little function should be pretty clear: it takes a database and returns an array of courses that are listed in that database.
The problem is that the return statement gets run before any of the database operations have run, and I get an empty list. When I set a breakpoint inside the database each loop, I can see that the rows are being found and that courses are being put into ret one by one, but these courses never become visible in the scope where courseList() was called.
const courseList = (database: sqlite3.Database): Course[] => {
let ret = new Array<Course>();
database.serialize();
database.each("select ID, Title from Course", (err: Error, row: Object) => {
ret.push(new Course(
row.ID,
row.Title
))
})
return ret;
}
Suggestions?
The calling code just wants to print information about courses. For example:
let courses = courseList(db);
console.log(courses.length); // logs 0, even though the db contains courses
database.each takes a complete callback. Use that to resume e.g.
const courseList = (database: sqlite3.Database, complete): Course[] => {
let ret = new Array<Course>();
database.serialize();
database.each("select ID, Title from Course", (err: Error, row: Object) => {
ret.push(new Course(
row.ID,
row.Title
))
}, complete);
return ret;
}
let courses = courseList(db, () => {
console.log(courses.length);
});
More
There are better ways to write this. Use promises https://basarat.gitbooks.io/typescript/content/docs/promise.html
The documentation is horrible : https://github.com/mapbox/node-sqlite3/wiki I would be tempted to look elsewhere (TS First) for a database solution. Its not worth the pain for me personally. YMMV.

Nightwatch-cucumber: How to use the Gherkin "And" keyword in step definitions?

I am using nightwatch-cucumber to write tests. I have a scenario that reads something like this:
Given I have loaded the dashboard page
And I have clicked on the result menu item
When I click on 'OK' in the prompt box
Then the results page is present
My question is: how do I create a step using the "And" keyword? e.g.:
And(/^I have clicked on the result menu item$/, () => {
return client.click('#results-box');
});
When I try this I get the following error:
ReferenceError: And is not defined
My solution was to use the "defineStep" method as follows:
defineSupportCode(({ Given, When, Then, defineStep }) => {
const And = defineStep;
Given(/^I have loaded the options page$/, () => {
return client
.url('http://localhost:3001/options')
.waitForElementVisible('body', 30000);
});
And(/^I have clicked on the toggle switchd$/, () => {
return client.click('#toggle-switch');
});
When(/^I click on the save button$/, () => {
return client.click('#save-button');
});
....
Switch the And to Given
defineSupportCode(({ Given }) => {
Given(/^I have clicked on the result menu item$/, () => {
return client.click('#results-box');
});
});

Resources