Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
console.log("Buying fruit, quantity: " + event.quantity);
model.stockCount -= event.quantity;
eventContext.commit();
});
router
.getEventObservable('model1', 'buyFruitEvent', esp.ObservationStage.committed)
.subscribe((event, eventContext, model) => {
// reacting to the buyFruitEvent we check if the shelf quantity requires refilling
var shouldRefreshFromStore = model.stockCount < 3;
console.log("Checking if we should refresh from store. Should refresh: " + shouldRefreshFromStore);
model.shouldRefreshFromStore = shouldRefreshFromStore;
});
router
.getEventObservable('model1', 'buyFruitEvent', esp.ObservationStage.committed)
.subscribe((event, eventContext, model) => {
// given we've sold something we flip a dirty flag which could be used by another
// // periodic event to determine if we should recalculate inventory
console.log("Flagging inventory recalculate");
model.shouldRecalculateInventory = true;
});
router.publishEvent('model1', 'buyFruitEvent', { quantity: 1 });
console.log(store.toString()); // Stock count: 9, shouldRefreshFromStore: false, shouldRecalculateInventory: true
router.publishEvent('model1', 'buyFruitEvent', { quantity: 8 });
console.log(store.toString()); // Stock count: 1, shouldRefreshFromStore: true, shouldRecalculateInventory: true
console.log();
};
console.log("Buying fruit, quantity: " + event.quantity);
model.stockCount -= event.quantity;
eventContext.commit();
});
router
.getEventObservable('model1', 'buyFruitEvent', esp.ObservationStage.committed)
.subscribe((event, eventContext, model) => {
// reacting to the buyFruitEvent we check if the shelf quantity requires refilling
var shouldRefreshFromStore = model.stockCount < 3;
console.log("Checking if we should refresh from store. Should refresh: " + shouldRefreshFromStore);
model.shouldRefreshFromStore = shouldRefreshFromStore;
});
router
.getEventObservable('model1', 'buyFruitEvent', esp.ObservationStage.committed)
.subscribe((event, eventContext, model) => {
// given we've sold something we flip a dirty flag which could be used by another
// // periodic event to determine if we should recalculate inventory
console.log("Flagging inventory recalculate");
model.shouldRecalculateInventory = true;
});
router.publishEvent('model1', 'buyFruitEvent', { quantity: 1 });
console.log(store.toString()); // Stock count: 9, shouldRefreshFromStore: false, shouldRecalculateInventory: true
router.publishEvent('model1', 'buyFruitEvent', { quantity: 8 });
console.log(store.toString()); // Stock count: 1, shouldRefreshFromStore: true, shouldRecalculateInventory: true
console.log();
};
export default class HeaderModel extends ModelBase {
constructor(
modelId:string,
router:Router
) {
super(modelId, router);
}
@observeEvent('init')
_onInit() {
_log.info(`Header model starting`);
}
@observeEvent('externalLinkClicked')
_onExternalLinkClicked() {
_log.info(`external link clicked`);
// TODO , if in open fin deal with launching the link
}
@observeEvent('minimiseClicked')
_onMinimiseClicked(e) {
_log.info(`minimise clicked`);
// TODO , if in open fin deal with launching the link
}
@observeEvent('maximiseClicked')
_onMaximiseClicked() {
_log.info(`maximise clicked`);
// TODO , if in open fin deal with launching the link
}
var runAcyncOperationWithRunActionExample = () => {
var myModel = {
foo:0,
backgroundOperations: 0
};
var router = new esp.Router();
router.addModel('myModelId', myModel);
router.getEventObservable('myModelId', 'getAsyncDataEvent').subscribe((e, c, m) => {
console.log('About to do async work');
m.backgroundOperations++;
setTimeout(() => {
router.runAction('myModelId', m2 => { // you could close over m here if you prefer
m2.backgroundOperations--;
console.log('Async work received. Updating model');
m2.foo = 1;
});
}, 2000);
});
router.publishEvent('myModelId', 'getAsyncDataEvent', { request: "someRequest" });
router.getModelObservable('myModelId').subscribe(m => {
console.log('Update, background operation count is: %s. foo is %s', m.backgroundOperations, m.foo);
});
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// notice_end
import esp from 'esp-js';
// note there are several concerns here that would exist in different areas of your architecture
// then are all together to demo the concepts.
// bootstrapping code
var router = new esp.Router();
router.registerModel(
"modelId",
{
staticDataInitialised: false,
price: 0,
staticData: { }
}
);
// price event processor code
router
.getEventObservable('modelId', 'priceChanged')
.do((model, event, eventContext) => console.log("price tick received"))
.where((model, event, eventContext) => model.staticDataInitialised)
.observe((model, event, eventContext)=> {
console.log("Price tick received and static data loaded, applying margin");
}
_listenForStaticDataReceivedEvent() {
// note you could wire up more advanced disposal of this stream (i.e. write
// a .takeUntilInclusive() extension method, you could also leave it
// open if you were to later expect events matching its eventType
this.addDisposable(this._router
.getEventObservable('modelId', 'userStaticReceivedEvent')
.subscribe((event, eventContext, model) => {
console.log("Adding static data [" + event + "] to model");
model.staticData.push(event);
})
);
}
}
var router = new esp.Router();
router.addModel("modelId", { staticData:[]});
var staticDataEventProcessor = new StaticDataEventProcessor(router);
staticDataEventProcessor.initialise();
console.log("Sending initialiseEvent");
router.publishEvent('modelId', 'initialiseEvent', {});
};
this.selectedEpic = null;
}
@esp.observeEvent(EventConsts.EPIC_SELECTED)
_onEpicSelected(event) {
this.selectedEpic = event.epic;
_.forEach(this.epics, epic => {
epic.isSelected = epic == event.epic;
});
if(this.selectedStory && this.selectedStory.epic !== this.selectedEpic) {
this.selectedStory.isSelected = false;
this.selectedStory = null;
}
}
@esp.observeEvent(EventConsts.STORY_SELECTED)
_onStorySelected(event) {
this.selectedStory = event.story;
_.forEach(this.allStories, story => {
story.isSelected = story == event.story;
});
}
// Gets called by the router when an event for this model has been processed by observers,
// great place for aggregate operations and/or validation.
postProcess() {
this.allStories = _.reduce(
this.epics, (result, epic) => {
return result.concat(epic.stories);
},
[]
);
}
@esp.observeEvent('MessageSent')
_observeMessageSent(event, context, model) {
this._messageService
.sendMessage(event.text, model.selectedThreadId, model.messageSection.threadName)
.subscribe(ack => {
/* ack received from send operation */
}
);
}
@esp.observeEvent('MessagesReceived')
_observeMessagesReceived(event, context, model) {
this._updateMessages(model);
this.hasChanges = true;
}
@esp.observeEvent('ThreadSelected', esp.ObservationStage.committed)
_observeThreadSelected(event, context, model) {
this._updateMessages(model);
this.threadName = event.threadName;
this.hasChanges = true;
};
_updateMessages(model) {
var rawMessages = model.rawMessagesByThreadId[model.selectedThreadId];
var messages = rawMessages.map(rawMessage => {
return new Message(
rawMessage.id,
rawMessage.authorName,
rawMessage.text,
new Date(rawMessage.timestamp));
}).sort(function (a, b) {
return a.time < b.time ? -1 : a.time > b.time ? 1 : 0;
});
export const defaultRequestForQuoteStateFactory = (): RequestForQuoteState => {
return {
rfqId: null,
currentQuoteId: null,
status: RfqStatus.Idle
};
};
export class RequestForQuoteStateHandlers {
constructor(/* can use DI if required for readonly access to other services */) {
}
@observeEvent(RfqEvents.requestQuote)
onRequestQuote(draft: RequestForQuoteState, event: RfqEvents.RequestQuoteEvent, model: CashTileModel /* , context: EventContext */) {
_log.info(`Requesting Quote for ${model.inputs.ccyPair} ${model.inputs.notional}`);
draft.rfqId = uuid.v4();
draft.status = RfqStatus.Requesting;
}
@observeEvent(RfqEvents.rfqUpdate)
onRfqUpdated(draft: RequestForQuoteState, event: RfqEvents.RfqUpdateEvent, model: CashTileModel /* , context: EventContext */) {
_log.info(`Quote received. RfqId ${event.rfqId} price: ${event.quote.price}`, event);
draft.status = event.status;
draft.quote = event.quote;
}
@observeEvent(RfqEvents.cancelRfq)
onCancelQuote(draft: RequestForQuoteState, event: RfqEvents.CancelRfqEvent, model: CashTileModel) {
_log.info(`Passing on quote ${draft.rfqId}`, event);
// esp dev tools is in beta ATM, bit heavy on the performance side of things.
// However feel free to uncomment these 2 lines and check it out.
// ctrl+alt+d brings up the tool window
//import espDevTools from 'esp-js-devtools';
//espDevTools.registerDevTools();
var _log:logger.Logger = logger.create('UnhandledModelError');
// The application uses a single esp router.
// Views can take the router instance it via import/require, however for model entities it's best not to rely on sourcing 'instance' style objects from import/require.
// This is because it makes the code a little less flexable, less portable and a little more magic.
// I tend to think of anything 'imported' as a static object, hard to test these.
// Typically you don't test the jsx/view and you don't really have any other options to get them the router.
// This is because they are created on a very different code path (i.e. via React `render`) and it's a bit over kill to pass the router via props (using the React context could be an alternative).
let router = new Router();
router.addOnErrorHandler(err => {
_log.error('Unhandled error in model', err);
});
export default router;