Success / Error Reporting from Service with Events / Observables - angularjs

Using some documentation I found online, I've written a service method for saving some data like this:
#Injectable
export class BrandService {
brands$: Observable<Brand[]>;
private _brandsObserver: Observer<Brand[]>;
private _dataStore: {
brands: Brand[]
};
constructor(private http: Http) {
this.brands$ = new Observable(observer => this._brandsObserver = observer).share();
this._dataStore = { brands: []};
}
saveBrand(brand: Brand) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post("http://localhost:8080/api/brands", JSON.stringify(brand), { headers: headers })
.map( (response: Response) => response.json()).subscribe(
data => {
this._dataStore.brands.push(data);
this._brandsObserver.next(this._dataStore.brands);
},
error => console.log("Could not create Brand"));
}
}
What this allows me to do is push updates to my collection of Brands and my table on the view will observe these changes and update automatically so I don't have to manually refresh it. All is well with the world.
My problem is that since I'm subscribing to the http.post in the service, my component now has no way of knowing whether or not this call succeeded, which also means that, since I'm showing the form in a modal dialog, I don't know if I should close the dialog or display errors. My component simply does this...
this._brandService.saveBrand(this.brandForm.value);
So, I was thinking that I should figure out a way to a) fire an event in the service that I'm listening for in the component for when good / bad things happen and act accordingly, or b) figure out some way of observing some other properties in the service that I can act on when those changes are detected. But I'm pretty new to all this observable stuff and I don't really even know where to begin.
data => {
this._dataStore.brands.push(data);
this._brandsObserver.next(this._dataStore.brands);
// fire some success event or
// update some observed property
},
error => {
// fire some failure event or
// update some observed property
}

You could do the subscribe() at call site
saveBrand(brand: Brand) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post("http://localhost:8080/api/brands", JSON.stringify(brand), { headers: headers })
.map( (response: Response) => response.json()).map(
data => {
this._dataStore.brands.push(data);
this._brandsObserver.next(this._dataStore.brands);
});
}
this._brandService.saveBrand(this.brandForm.value)
.subscribe(
value => onSuccess(),
error => onError());
If you still want to do some generic error handling in saveBrand you can use the catch operator (like used in Intercepting errors and subscribing to)

Related

How Filter Platform Events with LWC?

I have a lwc component that subscribes to the event WhatsAppMessage, and I have been trying to filter the event platform but I have not been able to get the expected result, since it does not respect my filter and it brings me all the results
This is my JS Code when I suscribe
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from
'lightning/empApi';
export default class PlatformEventMonitor extends LightningElement {
channelName = '/event/Sample__e';
isSubscribeDisabled = false;
isUnsubscribeDisabled = !this.isSubscribeDisabled;
subscription = {};
// Tracks changes to channelName text field
handleChannelName(event) {
this.channelName = event.target.value;
}
// Initializes the component
connectedCallback() {
// Register error listener
this.registerErrorListener();
}
// Handles subscribe button click
handleSubscribe() {
// Callback invoked whenever a new event message is received
const messageCallback = function(response) {
console.log('New message received: ', JSON.stringify(response));
// Response contains the payload of the new message received
};
// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe(this.channelName, -1, messageCallback).then(response => {
// Response contains the subscription information on subscribe call
console.log('Subscription request sent to: ', JSON.stringify(response.channel));
this.subscription = response;
this.toggleSubscribeButton(true);
});
}
// Handles unsubscribe button click
handleUnsubscribe() {
this.toggleSubscribeButton(false);
// Invoke unsubscribe method of empApi
unsubscribe(this.subscription, response => {
console.log('unsubscribe() response: ', JSON.stringify(response));
// Response is true for successful unsubscribe
});
}
toggleSubscribeButton(enableSubscribe) {
this.isSubscribeDisabled = enableSubscribe;
this.isUnsubscribeDisabled = !enableSubscribe;
}
registerErrorListener() {
// Invoke onError empApi method
onError(error => {
console.log('Received error from server: ', JSON.stringify(error));
// Error contains the server-side error
});
}}
What makes you think this would work? I don't recognise syntax for filtering like that? From what doc you took it?
You can set replay id to -1, -2 but you'll get all messages. https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation
You can filter them out manually in your app but it'll waste the daily limit of the events to can receive...
The proper way would be to define custom channel on top of your event. It's bit like writing a query/listview/report. But there is no UI for it, you'd have to craft a special JSON and send it to ord using tooling API.
https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_filter_section.htm

Is it possible to use the Symfony form component with React.js?

I am using the Symfony form component. I have many forms in my project.
To perfectly learn the form component was a long way to go, but now I love it. I love also the automatic validation and so on.
So. now I want to learn and use React.js in my project.
But it seems, there is no way I can use the validation and form builder like before for the projects? Am I right there?
While, in an API context, you won't use the Form Component to actually render your form in HTML format ($form->createView() method), you can still benefit from all the magic it offers: validation, form events, etc. API or not, I personnally think you should always use Form Types in Controller mutations.
For example, using FOSRestBundle, consider some simple Controller action looking like this:
/**
* #Rest\Put("posts/edit/{id}", name="posts.edit", requirements={"id"="\d+"})
*
* #param Post $post
* #param Request $request
*
* #return Post
*
* #throws BadRequestException
*
*/
public function edit(Post $post, Request $request): Post
{
$form = $this->createForm(PostType::class, $user);
$form->handleRequest($request);
$form->submit($request->request->all());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $post;
}
// Any error handling of your taste.
// You could consider expliciting form errors.
throw new BadRequestException();
}
Note that Post entity and PostType form must be created, of course. I won't be detailing it here as there is nothing special to say about them in this context.
Also note that we don't check if the form is submitted. Rendering the form as HTML being React's job in your case, this action won't be used to GET anything, it is exclusively a PUT route. This means that any Request coming there MUST be a PUT Request containing the correct data to be handled by our PostType, submitted in your case by an HTML form manually built in React.
Furthermore, slightly out of the question's scope, FOSRestBundle subscribes to whatever your action returns and automatically serializes it to the configured format (let's say JSON in your case, I guess). This means that our example of action can return two possible responses:
A Response with status code 200 containing our serialized Post. (You could also consider a 204 and return nothing.)
A Response with status code 400 containing whatever we want (let's say form errors).
Allow me to lead you to the FOSRestBundle's documentation.
You can use your form created with the formBuilder without problem.
You must get your form with axios and create a new component like this:
const url = 'localhost/post/new';
const ref = useRef(null);
const [form, setForm] = useState('');
const fetchData = () => {
axios.get(url))
.then(function (response){
setForm(response.data);
})
.catch(function (error){
//something
})
;
}
const MyComponent = () => {
useEffect(() => {
const element = ref.current.firstChild;
if (ref.current.firstChild === null)
return;
element.addEventListener('submit', () => {handleSave(event)});
return () => {
element.removeEventListener('submit', () => {handleSave(event)});
};
}, []);
return (
<div ref={ref} dangerouslySetInnerHTML={{ __html: form }} />
);
};
const handleSave = (event) => {
event.preventDefault();
let formData = new FormData(event.target)
let action = event.target.action;
let files = event.target.querySelectorAll('[type="file"]');
if (files)
files.forEach((file) => {
formData.set(file.name, file.files[0])
});
axios.post(action, formData)
.then(function (response) {
Swal.fire({
icon: 'success',
title: response.data.message,
showConfirmButton: false,
timer: 1500
})
//Do something else
})
.catch(function (error) {
error.response.status === 422 ?
setForm(error.response.data)
:
console.log(error);
});
}
return (<MyComponent/>);
So, now you can get the form with html components and render it with the React Component.
If you get some validation error you get a 422 status and you can replace the form with setForm().
In your Symfony Controller you must set something like this:
#[Route('/post/{state}/{id}', name: 'post', defaults: ['state' => null, 'id' => null])]
public function post(
?string $state,
?int $id,
Request $request,
EntityManagerInterface $em
): JsonResponse|Response
{
if ($state == 'new') {
$post = new Post();
$form = $this->createFormBuilder()
->add('title', TextType::class)
->add('content', TextareaType::class);
$form = $form->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() and $form->isValid()) {
$em->persist($post);
$em->flush();
return $this->json(['message' => 'post added!'], 200);
}
return $this->renderForm('{{ form(form) }}', [
'form' => $form
]);
}
}
I have reduced the function only for the form, but you can use it for all your requests.
Probably not because your form is intended for server use: validation/show errors/data normalization/sanatization/etc.
Usually you use React to display HTML and connect it to your server using an API.

Exporting an array within an ".then" doesnt work

I'm new to NodeJS and are only familiar with Java. I'm trying to create a file that creates objects based on a database and adds them to an array. This array I want to be able to export so that I can use it throughout the whole program, but when I try to export the array it doesn't work. I've tried googling and understanding but haven't come across anything that was helpful unfortunately.
I hope that someone can help me understand
I've tried calling module.exports after the ".then" call, but it just returns an empty array because its async.
I've also tried calling module.exports = teams inside the .then call but it didn't work neither.
var teams = [];
function assignTeamsToClasses() {
return new Promise((resolve, reject) => {
getAllTeamsInDb((teamList) => {
teamList.forEach((aTeam) => {
let newTeam = new Team(aTeam['teamid'], aTeam['teamname'], aTeam['teamrank']);
teams.push(newTeam);
});
resolve();
});
})
}
assignTeamsToClasses().then(() => {
module.exports = teams;
});
main.js
var teams = require('./initialize.js');
console.log(teams);
I expect it to return all teams that are in the database. I know that array is not empty when called within the ".then" call, but the export part does not.
Simple
the sequence require() + console.log() is synchronous
assignTeamsToClasses() is asynchronous, i.e. it updates teams at some unknown later point in time.
You'll have to design your module API to be asynchronous, e.g. by providing event listener interface or Promise interface that clients can subscribe to, to receive the "database update complete" event.
A proposal:
module.exports = {
completed: new Promise(resolve =>
getAllTeamsInDb(teams => {
const result = [];
teams.each(aTeam =>
result.append(new Team(aTeam.teamid,
aTeam.teamname,
aTeam.teamrank)
)
);
resolve(result);
})
),
};
How to use it:
const dbAPI = require('./initialize.js');
dbAPI
.completed
.then(teams => console.log(teams))
.catch(error => /* handle DB error here? */);
Every caller who uses this API will
either be blocked until the database access has been completed, or
receive result from the already resolved promise and proceed with its then() callback.

Can't use "this" in stomp client subscribe - React

I have my Spring-Boot service setup so I can send messages through websocket to my browser and it works.
//#MessageMapping
#RequestMapping(value = "/notify")
#SubscribeMapping("/notification")
#SendTo("/topic/notification")
public String sendNotification() throws Exception {
sendMessage();
return "Request to update Tanks has been sent!";
}
public void sendMessage() {
this.messagingTemplate.convertAndSend("/topic/notification", "IT WORKS");
}
Here's the console log from chrome:
<<< MESSAGE
destination:/topic/notification
content-type:text/plain;charset=UTF-8
subscription:sub-1519225601109-13
message-id:f2qodiqn-8
content-length:8
IT WORKS
I want to be able to receive a message from the service and update the state in react, so, that it refetches from the backend. This is what my client looks like:
var socket = new SockJS("http://localhost:6667/refresh");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('connected: ' + frame);
stompClient.subscribe('/topic/notification', function(notification){
console.log(notification.body);
//this.showNotification(JSON.parse(notification.body).content);
//this.showNotification(notification.body);
})
}, function(err) {
console.log('err', err);
});
And the fetch in componentDidMount()
fetch(`http://localhost:6666/front/objects`)
.then(result=>result.json())
.then(fuelTanks=>this.setState({fuelTanks}))
.catch(function(err) {
console.log('Could not fetch: ' + err.message);
}
)
I can't use this.showNotification(notification.body), hence I can't set the state to be able to refetch my objects. I tried making methods outside the class but then I can't use anything from the main class.
Is there a way to make react run componentDidMount again, or better, just access the fetch method in my class when I get a message from spring through the websocket?
Like this:
componentDidMount(){
var socket = new SockJS("http://192.168.1.139:8610/refresh");
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('connected: ' + frame);
stompClient.subscribe('/topic/notification', function(notification){
refetchTanks(); // call fetch tanks -> can't use "this"
})
}, function(err) {
console.log('err', err);
});
Thanks!
I know, it is a bit old question, but since it pops every time when you search for stomp issue, i thought of answering it. The way to access this in callbacks is to bind callbacks with this first, then the whole of object can be accessed in the callback.
Example:
connectCallBack(){
this.setState({loading:false})
}
errorCallback=()=>{
}
componentDidMount() {
axios.post('http://localhost:8080/subscribe', null, { params: {
deviceId
}})
.then(response => response.status)
.catch(err => console.warn(err));
const socket = new SockJS('http://localhost:8080/test');
const stompClient = Stomp.over(socket);
//stompClient.connect();
stompClient.connect( {}, this.connectCallBack, this.errorCallback);
If see above code both callbacks can access this.
I tried everything to be able to use my class methods and the state in stompClient's .subscribe method. I was able to connect and reconnect if the service died, nevertheless it wasn't working.
I decided to use react-stomp, which worked. I could use a class method in onMessage=.... This is what my code looks like:
<SockJsClient
url = 'http://localhost:8610/refresh/'
topics={['/topic/notification']}
onConnect={console.log("Connection established!")}
onDisconnect={console.log("Disconnected!")}
onMessage={() => this.update()} <------ this method performs a new GET
request
debug= {true}
/>
I also had to send the message in a specific way on the server side, since I was getting a JSON error when sending a string.
this.messagingTemplate.send("/topic/notification", "{"text":"text"}");
<<< MESSAGE
destination:/topic/notification
content-type:text/plain;charset=UTF-8
subscription:sub-0
message-id:aaylfxl4-1
content-length:49
{
"text": "text"
}
It currently works, but I am curious if there are other, better solutions to this issue.
EDIT: a much better solution here! Use the code from the first post and create a variable before connect to be able to access this like this var self = this;, then just access is as self.update() after subscribe!

API requests as a result of changes to domain objects

I'm having trouble wrapping my head around how to handle api calls as a result
of updates to data only the store should know how to perform (business logic).
The basic flow is as follows:
AdComponent#_changeGeoTargeting calls the action creator
UnpaidIntents#updateTargeting which dispatches an
ActionTypes.UPDATE_TARGETS action which is handled like so:
AdStore.dispatchToken = Dispatcher.register(action => {
switch(action.type) {
case ActionTypes.UPDATE_TARGETS:
// Business logic to update targeting from an action payload.
// `payload` is an object, e.g. `{ geos: geos }`, `{ devices: devices }`,
// etc.
_unpaid.targeting = _calcTargeting(
_unpaid.targeting, action.payload);
// Ajax call to fetch inventory based on `Ad`s parameters
WebAPIUtils.fetchInventoryPredictions(
_unpaid.start, _unpaid.end, _unpaid.targeting)
.then((resp) => {
var key = _makeCacheKey(
_unpaid.start, _unpaid.end, _unpaid.targeting);
// Updates store's inventory cache
_updateInventoryCache(key, resp);
})
.catch((error) => {
// How can I handle this error? If this request
// was executed inside an action I could have my
// `NotiticationsStore` listening for
// `ActionTypes.INVENTORY_PREDICTIONS_ERROR`
// and updating itself, but I can't dispatch here.
});
break;
default:
return true;
}
AdStore.emitChange();
return true;
});
The problem being that this call can't dispatch other actions since it's in a
store.
I could make the call in the action creator, but that requires it to know how
to update the Ad. I was under the impression that action creators should
be dumb "dispatcher helper methods", and something like this would violate those
principles:
UnpaidIntents.updateTargeting = (ad, value) => {
var targeting = _calcTargeting(ad.targeting, value);
WebAPIUtils.fetchInventoryPredictions(ad.start, ad.end, targeting)
.then((resp) => {
Dispatcher.dispatch({
type: ActionTypes.UPDATE_TARGETING,
payload: {
targeting: targeting,
inventory: resp,
},
});
})
.catch((error) => {
Dispatcher.dispatch({
type: ActionTypes.INVENTORY_PREDICTIONS_ERROR,
payload: error,
});
});
};
Would breaking out _calcTargeting into an AdUtils module and using that as
my business logic layer be the way to do this? I'm afaid if I have business
logic in utils and possibly also stores that things will get messy very quickly.
Can anyone give some guidance here?

Resources