Vuex ORM models dependency cycle - vuex

In the store, I have two related models: Company and User
User
import { Model } from '#vuex-orm/core';
import { Company } from './models';
export class User extends Model {
static entity = 'users';
static fields() {
return {
company: this.belongsTo(Company, 'company_id'),
};
}
}
export default User;
Company
import { Model } from '#vuex-orm/core';
import { User } from './models';
export class Company extends Model {
// This is the name used as module name of the Vuex Store.
static entity = 'companies';
static fields() {
return {
account_manager: this.belongsTo(User, 'account_manager_id'),
};
}
}
export default Company;
To avoid dependency cycle, I closely followed the solution from https://vuex-orm.org/guide/model/single-table-inheritance.html#solution-how-to-break-cycles
and import Company and User into models.js
Models
export * from './company';
export * from './user';
Yet I still get the dependency cycle error from the linter.
I run out of ideas.
Code sample: https://github.com/mareksmakosz/vuex-orm-dependency-cycle

This is just ESLint enforcing the rule, you can't avoid it if you're using airbnb. Consider eslint:recommended if it's truly a pain.
Alternatively, if you want to keep airbnb and your models separated, I suggest dropping the imports and define your relations using entity as a string.
this.belongsTo('companies', 'company_id')
this.belongsTo('users', 'account_manager_id')

Related

vue.js - class component - Update view when RxJs Observable change data

Disclaimer: I'm a beginner in using Vue.js, and being used to Angular I went the Class Component way. I know that not the proper Vue.js way, but this is a fun pet project, so I elected to do it in a unusual way in order to try new things.
I have a simple component, "MyForm", written using Typescript and the Class Component Decorator.
To simulate a service, I made a Typescript class "MyService", that contain methods simulating an API call using an RxJs Observable objects with a delay. The the service function update the data contained in another class "MyDataStore", which is then read by the component to update the view.
But when the observable returns and changes the Data in the Store, it does not update the displayed data (until the next clic on the button).
The component
<template>
<v-app>
<pre>
<v-btn #click="clickBouton()">Load</v-btn>
Form counter: {{counter}}
Service counter: {{service.counter}}
Store counter : {{store.counter}}
RxJs data : {{store.data}}
</pre>
</v-app>
</template>
<script lang="ts">
import { MyDataStore } from '#/services/MyDataStore';
import { MyService } from '#/services/MyService';
import Vue from 'vue'
import Component from 'vue-class-component';
#Component
export default class MyForm extends Vue {
public counter = 0;
public store = MyDataStore;
public service = MyService;
clickBouton(){
this.counter++;
MyService.Increment()
MyService.getData();
}
}
</script>
The service
import { of, from, concatMap, delay } from 'rxjs';
import { MyDataStore } from './MyDataStore';
export class MyService {
public static counter = 0
// Update the data store with a new value every 10s
static getData(){
from(["A", "B", "C", "D"]).pipe(concatMap(item => of(item).pipe(delay(10000)))).subscribe((res: any) => {
MyDataStore.data = res;
});
}
static Increment(){
MyDataStore.counter++;
MyService.counter++
}
}
The "DataStore"
export class MyDataStore {
static data: string;
static counter = 0;
}
Any help or tutorial are welcome.
Hey In the end you get a observable. You need to subscribe a value of your component to it and descubscribe it if you destroy your component. If you are using Vue 2 you can use async pipes/filter in order to automate this process.
I found this tutorial:
https://medium.com/#p.woltschkow/a-better-practice-to-implement-http-client-in-vue-with-rxjs-c59f93bfa439

Spartacus Multisite Site Specific Configuration

We'd like to store some site-specific config on the frontend in Spartacus.
For example: Each site (of a multisite setup) has a different Google API Key.
Right now, I've built a CONFIG_INITIALIZER factory, like the following. But with the fake scoping and all, it does not seem the correct way to do this.
import { Inject, Injectable } from '#angular/core';
import { ConfigInitializer, ConfigInitializerService, deepMerge } from '#spartacus/core';
import { StoreFinderConfig } from '#spartacus/storefinder/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { MultiSiteConfigChunk } from './multisiteconfig-tokens';
#Injectable({ providedIn: 'root' })
export class MultisiteConfigInitializer implements ConfigInitializer {
// Fake scoping :(
readonly scopes = ['all'];
readonly configFactory = () => this.resolveConfig().toPromise();
constructor(
protected configInit: ConfigInitializerService, #Inject(MultiSiteConfigChunk) private multiSiteConfig: Array<any>) {
}
protected resolveConfig(): Observable<StoreFinderConfig> {
return this.configInit.getStable('context.baseSite').pipe(
map((config) => {
const mergedConfig = deepMerge(...this.multiSiteConfig);
return mergedConfig[config.context.baseSite];
})
);
}
}
What would be the recommended way to get be able to do this?
You can check this doc first: https://sap.github.io/spartacus-docs/automatic-context-configuration/#adding-a-custom-context
If you are using automatic context configuration, you also can try this:
extends SiteContextConfigInitializer (inject your multiSiteConfig in the child class); replace SiteContextConfigInitializer using the child in providers.
replace getConfig function in child class to add the Google API Key to site-context.

What is the best way to handle Page Objects for different environments?

We have two sits to support, for an example US and Canada. Some pages are exactly the same and some have different options. How I can use page object pattern define pages for this situation and reduce the duplicates?
Let's take the Login page, For US as follows,
import { by, element, ElementFinder } from 'protractor';
export class Homepage {
public startNowButton: ElementFinder;
public signinLink: ElementFinder;
constructor() {
this.startNowButton = element(by.css('button[sso-modal="SignUp"]'));
this.signinLink = element(by.linkText('Sign in'));
}
}
For Canada, there is an additional checkbox,
export class Homepage {
public startNowButton: ElementFinder;
public signinLink: ElementFinder;
public loanPurposeRadio: string;
constructor() {
this.startNowButton = element(by.css('button[sso-modal="SignUp"]'));
this.signinLink = element(by.linkText('Sign in'));
this.loanPurposeRadio = '[ng-form="loanPurposeField"] label';
}
}
If I want to support both sites then what is the best way to model page objects this kind of situations rather creating two classes? Thanks
I am not JS expert. I did not verify the below code. I am explaining based on how i would achieve that in Java. you can modify accordingly.
I would be creating an abstract class HomePage which defines all the common functionalities for all locales. USHomePage, CAHomePage classes should extend the HomePage. Or, You can also use USHomePage as Base class HomePage and CAHomePage will extend this.
Now in the below example, you have all the functionalities of US home page & you have also added specific features of CA.
For ex:
export class CAHomepage extends HomePage {
public loanPurposeRadio: string;
constructor() {
super();
this.loanPurposeRadio = '[ng-form="loanPurposeField"] label';
}
}
Now you could maintain some of kind factory class to return specific instance of HomePage depends on the site you test.
var homePageFactory = {
"US": () => { return new HomePage() },
"CA": () => { return new CAHomePage() },
"UK": () => { return new UKHomePage() }
}
Based on the locale/country, you can access specific home page. Your tests are not tied to specific site & instead they are very generic. Depends on the site you test, they behave differently.
var lang = "US"
var homePage = homepageFactory[lang]();
homePage.login();
homePage.register();

singleton object in react native

I'm new in react native.I want store multiple small small strings to common singleton object class and want to access it from singleton object for all component. Can anyone help me singleton object implementation for react native.
Ex
Component 1 -- Login button -- >> success --> need to store userID into singleton object.
Component 2 --> get stored userID from singleton object. How can i implement it.
Here is a simple way of doing it...
export default class CommonDataManager {
static myInstance = null;
_userID = "";
/**
* #returns {CommonDataManager}
*/
static getInstance() {
if (CommonDataManager.myInstance == null) {
CommonDataManager.myInstance = new CommonDataManager();
}
return this.myInstance;
}
getUserID() {
return this._userID;
}
setUserID(id) {
this._userID = id;
}
}
And here is how to use it...
import CommonDataManager from './CommonDataManager';
// When storing data.
let commonData = CommonDataManager.getInstance();
commonData.setUserID("User1");
// When retrieving stored data.
let commonData = CommonDataManager.getInstance();
let userId = commonData.getUserID();
console.log(userId);
Hope this works out for you :)
I suggest making a static class that stores data using AsyncStorage.
You mentioned in a comment that you are already using AsyncStorage, but don't like spreading this functionality throughout your app. (i.e. try-catches all over the place, each component needing to check if a key is available, etc.) If this functionality were in a single class, it would clean up your code a lot.
Another bonus to this approach is that you could swap out the implementation pretty easily, for example, you could choose to use an in-memory object or AsyncStorage or whatever and you would only have to change this one file
NOTE: AsyncStorage is not a safe way to store sensitive information. See this question for more info on the security of AsyncStorage and alternatives.
That said, this is how I imagine a global data holder class might look:
export default class dataManager {
static storeKeyValue(key, value) {
// your choice of implementation:
// check if key is used
// wrap in try-catch
// etc.
}
static getValueForKey(key) {
// get the value out for the given key
}
// etc...
}
Then to use this class anywhere in your app, just import wherever it's needed like so:
import dataManager from 'path/to/dataManager.js';
// store value
dataManager.storeKeyValue('myKey', 'myValue');
// get value
const storedValue = dataManager.getValueForKey('myKey');
EDIT: Using Flux, Redux, or a similar technology is probably the preferred/suggested way to do this in most cases, but if you feel the Singleton pattern works best for your app then this is a good way to go. See You Might Not Need Redux
There is a workaround for this, react native packager require all the modules in the compilation phase for a generating a bundle , and after first require it generates an internal id for the module, which is from then on referenced in the whole run-time memory , so if we export an instance of a class from the file, that object will be referenced every-time whenever that file is imported .
TLDR;
Solution I :
class abc {
}
module.exports = new abc()
Solution II : I assume you want to get your strings which are static and wont change , so you can declare them as static and access them directly with class name
FYI :this works with webpack also.
I might be too late for this, but I might as well share my own implementation based on Yeshan Jay's answer.
export default class Data {
static instance = null;
_state = {};
static get inst() {
if (Data.instance == null) {
Data.instance = new Data();
}
return this.instance;
}
static get state() {
return Data.inst._state;
}
static set state(state) {
Data.inst._state = state;
}
static setState(state) {
Data.inst._state = {...Data.inst._state, ...state}
}
}
And here's how you use it. It's pretty much mimicking React Component's state behavior, so you should feel at home with little to no adjustment, without the need to frequently modify the Singleton to add new properties now and then.
import Data from './Data'
// change the whole singleton data
Data.state = { userId: "11231244", accessToken: "fa7sd87a8sdf7as" }
// change only a property
Data.setState ({ userId: "1231234" })
// get a single property directly
console.log("User Id: ", Data.state.userId)
// get a single property or more via object deconstruction
const { userId, property } = Data.state
console.log("User Id: ", userId)
TS Class Example:
export class SingletonClass
{
private static _instance: SingletonClass;
public anyMetod(_value:any):any
{
return _value;
}
public static getInstance(): SingletonClass
{
if (SingletonClass._instance == null)
{
SingletonClass._instance = new SingletonClass();
}
return this._instance;
}
constructor()
{
if(SingletonClass._instance)
{
throw new Error("Error: Instantiation failed: Use SingletonClass.getInstance() instead of new.");
}
}
}
Use:
SingletonClass.getInstance().anyMetod(1);

Is it possible to make a function or class available to all views in Aurelia?

The use case is as follows: We would like to have elements hidden or shown, based on the user's permissions.
The ideal way would be something like this:
<div if.bind="foo != bar && hasPermission('SOME_PERMISSION')"></div>
hasPermission() would in that case be a function that was automatically injected into all viewmodels.
Is that possible? I know we could use base classes for this, but we'd like to avoid that to stay as flexible as possible.
If you're willing to pay the price of a global function (global as in window), import it in your app-bootstrap file, like so:
has-permission.js
export function hasPermission(permission) {
return permission.id in user.permissions; // for example...
}
main.js
import 'has-permission';
export function configure(aurelia) {
// some bootstrapping code...
}
If the service you want to publish globally is a view, you can sidestep exposing it on the window and tell Aurelia's DI to make it available everywhere so you won't have to declare it in every dependent client.
To do so, pass its module ID in the FrameworkConfiguration#globalResources() configuration function:
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.globalResources('my-kick-ass-view', 'my-awesome-converter');
aurelia.start().then(a => a.setRoot());
}
If you have a service which deals with user permission, it can be injected in all your view-models.
export class UserPermissionService
{
hasPermission(user, permission)
{
return false;
}
}
#inject(UserPermissionService)
export class Users {
userPermissionService;
constructor(userPermissionService) {
this.userPermissionService = userPermissionService;
...
}
hasPermission(user, p)
{
return this.userPermissionService.hasPermission(user, p);
}
}
If you still don't like this, other options are:
a value converter http://aurelia.io/docs.html#/aurelia/binding/1.0.0-beta.1.2.1/doc/article/binding-value-converters
a custom attribute (similar to if it will hide the element)
http://www.foursails.co/blog/custom-attributes-part-1/
depending on what you need, both can use the UserPermissionService singleton from above
Add a .js file in your folder, with export function
ex: utility.js
export function hasPermission(permission) {
return true/false;
};
import the function in view-model
import {hasPermission} from 'utility';
export class MyClass{
constructor(){
this.hasPermission = hasPermission;
}
}
view.html
<div if.bind="foo != bar && hasPermission('SOME_PERMISSION')"></div>