Avoid circular dependency when using interface in Nestjs/GraphQL - graphql

I was following the code first approach to defining a GraphQL interface in the Nestjs docs.
However, the resolveType() requires that you return a class instance and forces me to import the classes that implements the interface (I have the classes in different files); this creates circular depedencies amongst my classes and the interface files.
Example:
book.interface.ts:
import { ColoringBook } from './coloring-book.model.ts
import { TextBook } from './textbook.model.ts
#InterfaceType(resolveType(book) {
if (book.colors) {
return ColoringBook;
}
return Textbook;
})
abstract class Book {
// class members...
}
coloring-book.model.ts:
import { Book } from './book.interface.ts';
#ObjectType({ implements: Book})
class ColoringBook implements Book {
// class members...
}
textbook.model.ts:
import { Book } from './book.interface.ts';
#ObjectType({ implements: Book})
class Textbook implements Book {
// class members...
}
I've tried this like:
resolveType(book) {
if (book.colors) {
return forwardRef(() => ColoringBook);
}
return forwardRef(() => TextBook);
}
but that doesn't help as I still need to import the class and it doesn't actually resolve at runtime.
What would be a best practice way of avoiding this circular dependency short of consolidating everything to one file?

I ended up following how it was done here:
#InterfaceType({
resolveType: value => value.constructor.name,
})
I am not sure if this has any side effects underlying but it definitely looks cleaner and doesn't require me to circular import.

Building on your answer:
It seems like you can simply pass the class name instead of the JS class, which results in:
book.interface.js
// no import
#InterfaceType(resolveType(book) {
if (book.colors) {
return 'ColoringBook';
}
return 'Textbook';
})
abstract class Book {
// class members...
}
In my case, value.constructor.name was systematically the Interface name (Book instead of <Specifier>Book)

Related

Overcomplicating design patterns

I am trying to solve a design problem with design patterns. Now that I have the basics I am fairly sure that I overcomplicated it a lot. I seem to have multiple empty interfaces, and I probably could do with less with a different design. Also I'm not sure if future developers on the project will have an easy time figuring out this tangle.
I've made a mockup of the structure of the classes. The example is dumbed down to two service types (cf BaseAnimalService extensions), in the project there are more. There are also more BaseStrategy implementations.
At first I want do differentiate between a context for a CatService or DogService. This is done using a Map in the BaseStrategy class, which has the BaseAnimalService as value to enable polymorphism between the Cat/DogService. Based on the generic type of the BaseStrategy, implemented in the Dog/CatStrategy a different configurationMap is used, which in turn, based on the type of the criteria, loads one or the other implementation of the Dog/CatService.
The configuration maps are defined in the spring.xml file.
Since the Dog/CatService both implement an extra interface, cf. SomeOtherCat/DogService, which is external to my design, the Dog/CatService both have have empty interfaces too. SomeOtherCatService and SomeOtherDogService aren't related and aren't editable so I can't use them polymorphically, which is the reason for the Base/Cat/DogService interfaces.
I thought about making the BaseStrategy a StrategyFactory which returns a Cat/DogStrategy which in turn checks the type of the criteria for which BaseAnimalService to use. But since both these strategies use the same logic for their strategies, this would mean I would have to create another base class.
What do you think? Any suggestions on what would be a better design for this problem? Or any improvements to the current one?
class BaseStrategy<T extends BaseAnimalService> {
private ContextService contextService;
private Map<String, BaseAnimalService> configurationMap;
T getService() {
return configurationMap.get(contextService.getCurrentContext());
}
}
interface BaseAnimalService {
//empty
}
interface DogService extends BaseAnimalService {
//empty
}
interface CatService extends BaseAnimalService {
//empty
}
class DogStrategy extends BaseStrategy<DogService> {
//empty
}
class CatStrategy extends BaseStrategy<CatService> {
//empty
}
class BritishShortHairServiceImpl implements CatService, SomeOtherCatService {
#Override //source: SomeOtherCatService, same for other implementations below
void pur() {
//pur
}
}
class LionServiceImpl implements CatService, SomeOtherCatService {
#Override
void pur() {
//pur
}
}
class PitBullServiceImpl implements DogService, SomeOtherDogService {
#Override
void wagTail() {
//wag tail
}
}
class ChihuahuaServiceImpl implements DogService, SomeOtherDogService {
#Override
void wagTail() {
//wag tail
}
}
class CatPerson {
private BaseStrategy<CatService> catStrategy;
void pet() {
catStrategy.getService().pur();
}
}
class DogPerson {
private BaseStrategy<DogService> dogStrategy;
void feed() {
dogStrategy.getService().wagTail();
}
}
Relevant spring.xml snippet:
<bean id="baseStrategy" abstract="true"
class="com.animals.services.BaseStrategy">
<property name="contextService" ref="contextService"/>
</bean>
<bean id="catServiceStrategy"
class="com.animals.services.CatStrategyImpl"
parent="baseStrategy">
<property name="strategyConfigurationMap">
<map>
<entry key="CONTEXT1" value-ref="britishShortHairService"/>
<entry key="CONTEXT2" value-ref="lionService"/>
</map>
</property>
</bean>
<bean id="dogServiceStrategy"
class="com.animals.services.DogStrategyImpl"
parent="baseStrategy">
<property name="strategyConfigurationMap">
<map>
<entry key="CONTEXT1" value-ref="pitbullService"/>
<entry key="CONTEXT2" value-ref="chihuahuaService"/>
</map>
</property>
</bean>
I am not familiar with Spring or its Context Service model, so I am approaching this question from a general, language-independent OOP perspective.
In my opinion you need to be thinking about ways that you can pass configurations through the constructor (dependency injection) rather than switching based on maps. You need more "has a" relationships (composition) and less "is a" relationships (inheritance).
An AnimalService can take an animal object as an argument to the constructor. We can say that an AnimalFeedbackBehavior must include methods for positiveFeedback(), neutralFeedback(), and negativeFeedback() -- but how those methods are implemented can vary from animal to animal. A Cat would purr() in response to a positive interaction but a Dog would wagTail().
An AnimalOwner can feed() any animal and trigger AnimalFeedbackBehavior.positiveFeedback(). The AnimalOwner does not need to know what that behavior does behind the scenes. It does not even need to know what species of animal it has. All it needs to know is that this method exists.
interface AnimalFeedbackBehavior {
positiveFeedback(): void;
neutralFeedback(): void;
negativeFeedback(): void;
}
class AnimalOwner {
private animal: AnimalFeedbackBehavior;
// pass animal instance to the constructor
constructor( animal: AnimalFeedbackBehavior) {
this.animal = animal;
}
// trigger positive feedback when feeding
feed() {
this.animal.positiveFeedback();
}
}
class Cat implements AnimalFeedbackBehavior {
purr() {
//do something
}
positiveFeedback() {
this.purr();
}
/* ... rest of class ... */
}
Typescript Playground Link
Here we assumed that feed is always a positive interaction. But what if we want different animals to have different reactions to the same interactions? chase() might be positive for a Dog but negative for a Cat. A naïve approach would be to switch the feedback based on a map. But an ideal design allows for maximum abstraction where the AnimalOwner doesn't need to know anything about the animal types.
Let's try a totally different setup.
If you are dealing with a small set of behaviors, we could require that the animal has a response for each behavior, rather than positive/neutral/negative.
interface AnimalBehavior {
feedResponse(): void;
chaseResponse(): void;
}
But this could get unwieldy quickly. We could define an animal with a respond method that responds to some sort of generic action object. In the implementation, it can do something in response to the action or just ignore it.
This setup also makes the composition of multiple overriding behaviors more intuitive since we can go through a chain of respond functions until one handles it. We want to know it there was a response or not so we need to return something from the response function. If it's basically void then we can return a boolean flag that's true if it responded. If a response should return a value than you would return either that value or undefined.
interface Action {
type: string;
}
// we may want to attach some sort of data
interface ActionWithData<T> extends Action {
type: string;
data: T;
}
interface AnimalBehavior {
respond( action: Action ): string | undefined;
}
class Animal implements AnimalBehavior {
// an animal has an array of behavior responders
// as written, the earlier behaviors in the array override later ones
private behaviors: AnimalBehavior[];
// can instantiate an animal with multiple behaviors
constructor( behaviors: AnimalBehavior[] = [] ) {
this.behaviors = behaviors;
}
// can also add behaviors after the fact
public addOverride( behavior: AnimalBehavior ) {
this.behaviors = [behavior, ...this.behaviors];
}
// loop through behaviors until one responds
public respond (action: Action): string | undefined {
for ( let element of this.behaviors ) {
// could be a response or might be undefined
const response = element.respond(action);
if ( response ) {
return response;
}
}
// could do something here if no behaviors responded
return undefined;
}
}
class AnimalOwner {
private animal: AnimalBehavior;
// pass animal instance to the constructor
constructor( animal: AnimalBehavior) {
this.animal = animal;
}
// animal can respond to the feed action, or not
feed(): string | undefined {
return this.animal.respond({type: 'feed'});
}
chase(): string | undefined {
return this.animal.respond({ type: 'chase' });
}
}
These implementations feel sloppy at the moment. Right now none of them use this so it's pointless to use a class. But just to give you an idea:
class DogBehavior implements AnimalBehavior {
respond(action: Action): string | undefined {
switch (action.type) {
case 'feed':
return "Wag Tail";
case 'chase':
return "Run Around";
default:
return undefined;
}
}
}
class PuppyBehavior implements AnimalBehavior {
respond(action: Action): string | undefined {
switch (action.type) {
case 'feed':
return "Jump";
default:
return undefined;
}
}
}
class ChihuahuaBehavior implements AnimalBehavior {
respond(action: Action): string | undefined {
switch (action.type) {
case 'feed':
return "Yip";
default:
return undefined;
}
}
}
Both the Animal composition and the individual behaviors implement AnimalBehavior, so an AnimalOwner can take a DogBehavior directly or it can take an Animal composed of a DogBehavior and some other behaviors.
const owner1 = new AnimalOwner(new DogBehavior());
let res = owner1.feed(); // is "Wag Tail"
The order matters. If we have a chihuahua puppy, we need to decide whether ChihuahuaBehavior overrides PuppyBehavior or vice-versa.
// prioritizes puppy
const owner2 = new AnimalOwner(new Animal([new PuppyBehavior(), new ChihuahuaBehavior(), new DogBehavior()]));
res = owner2.feed(); // is "Jump" from PuppyBehavior
res = owner2.chase(); // is "Run Around" from DogBehavior because not overwritten
// prioritizes chihuahua
const owner3 = new AnimalOwner(new Animal([new ChihuahuaBehavior(), new PuppyBehavior(), new DogBehavior()]));
res = owner3.feed(); // is "Yip" from ChihuahuaBehavior
Typescript Playground Link

How to separate 'Implemented Conditional Validation Service/Function' in Angular-8 while using Reactive-Forms

I have implemented conditional Validation in my Component.
I am trying to separate the validation logic from my component to another component/service.
Demo Link : http://StackBlitz%20https://stackblitz.com/edit/angular-amr86r
You can easily apply conditional validation using #rxweb/reactive-form-validators. I have applied required validation through both validator as well as decorator based approach. Please refer to the working example.
Using Decorator based approach:
You just need to apply #required() decorator with the condition you want to apply on your model-property.
Here is the complete model code:
import { required } from "#rxweb/reactive-form-validators"
export class UserInfo {
#required()
firstName: string;
#required({conditionalExpression:'x => x.firstName == "Bharat"' })
lastName: string;
}
Using Validator based approach:
For validator based approach, you just need to mention RxwebValidators.required() with the condition you want to apply on your form-control.
Here is the complete component code:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder } from "#angular/forms"
import { RxwebValidators } from '#rxweb/reactive-form-validators';
#Component({
selector: 'app-validator-based-validator',
templateUrl: './validator-based.component.html'
})
export class ValidatorBasedValidationComponent implements OnInit {
validatorBasedFormGroup: FormGroup
constructor(
private formBuilder: FormBuilder )
{ }
ngOnInit() {
this.validatorBasedFormGroup = this.formBuilder.group({
firstName:['', RxwebValidators.required()],
lastName:['', RxwebValidators.required({conditionalExpression:'x => x.firstName == "Bharat"' })]
});
}
}
Note : if you will use validator approach then, You can create a function in a separate file and use that respective function in the condtional expression property. In anyway, the model file will be separated in decorator based approach.

How to create single observable value?

I've got a top-level Controller object that is holding a reference to three objects (MyObject). I'd like to position these precisely on the page at any time, but I would like each object to also be editable, and I'm not really sure how to do that.
So far, I've got a class that extends ItemFragment and displays my individual items, like this:
class MyObjectFragment(o: MyObject) : ItemFragment<MyObject>() {
override val root = hbox {
...
}
}
Meanwhile, I have a top-level View with a reference to my controller, like this:
class TopLevelView : View() {
val controller = TopLevelController()
override val root = hbox {
add(MyObjectFragment(controller.myObject1))
...
add(MyObjectFragment(controller.myObject2))
...
add(MyObjectFragment(controller.myObject3))
}
}
And right now, all I have for the top level controller is this:
class TopLevelController() : Controller() {
val myObject1 = MyObject()
val myObject2 = MyObject()
val myObject3 = MyObject()
}
I'm trying to figure out what I need to do to wrap these objects as observable values. My first attempt was to add something like this to the init method of MyObjectFragment:
class MyObjectFragment(o: MyObject) : ItemFragment<MyObject>() {
init {
itemProperty.bind(o)
}
...
}
However, that method only takes an ObservableValue<MyObject>. What is the best way to get that to tie all of this together?
You can create an observable list of your objects like so:
class TopLevelController() : Controller() {
val myObjects = FXCollections.observableArrayList<MyObject>(MyObject(), MyObject(), MyObject())
}
Then in your TopLevelView, you can bind this list to a layout node's children property, and inflate the proper Fragment for each object:
class TopLevelView : View() {
val controller = TopLevelController()
override val root = hbox {
bindChildren(controller.myObjects) {
MyObjectFragment(it).root
}
}
}
I'll admit your requirements seem a little vague to me without more information. It'd be helpful to know more of what you want from the item fragments. Are they going to be in a list view or table? Or something more dynamic? And how exactly would they be editing? Would there be a save button or would you expect any input to commit those changes immediately?
import tornadofx.*
class MyObject() {
//val someProperty = SimpleObjectProperty<Something>()
//var some by someProperty
}
class MyObjectModel(myObject: MyObject? = null) : ItemViewModel<MyObject>(myObject) {
//val someBinding = bind(MyObject::someProperty)
}
class MyObjectFragment : ItemFragment<MyObject>() {
val model: MyObjectModel by inject()
override val root = hbox {
label("This is an MyObject Fragment")
//you would bind some control to the model binding in here. For example:
//textfield(model.someBinding)
}
init {
itemProperty.value = model.item
model.bindTo(this)
}
}
class TopLevelController : Controller() {
val myObject1 = MyObject()
val myObject2 = MyObject()
val myObject3 = MyObject()
}
class TopLevelView : View() {
val controller: TopLevelController by inject()
override val root = vbox {
add(setUpObjectFragment(controller.myObject1))
add(setUpObjectFragment(controller.myObject2))
add(setUpObjectFragment(controller.myObject3))
}
fun setUpObjectFragment(obj: MyObject) = find<MyObjectFragment>(Scope(MyObjectModel(obj)))
}
It also seems you're new and are missing a lot of key concepts to utilize from TornadoFX. Using find for instance, is really important for Fragments and Views so they have the proper life cycle.
Then there's Scopes which help with being able to call certain Components with injection.
And finally, there are Model classes, most importantly ItemViewModel which gives you the most functionality with editing, like being able to rollback and commit changes as well as to mark properties as required and add validate filters.
If this isn't a satisfactory solution, please give us more information on what you want, as I might be able to provide a more elegant and concise solution. If these concepts are confusing, please look at Edvin's guide.

Test with Lumen package

I develop lumen package and I don't know test this.
In my package, I use global method config() and abort() but this methods exist with bootstrap/app.php and I have'nt this file in my package.
I'm thinking redefine this methods with dummies class but I have to write only one test method in test class when I test a method with a changement in the config to can re-call an antoher config dummy class .
It's not practical and I guess there's better.
I can share code if you want.
--- Edit
This is example :
Class CheckAuthorizationTest
public function testCanSeeOtherUserRoles()
{
$this->assertTrue(CheckAuthorization::canSeeOtherUserRoles($user, $user));
}
Class CheckAuthorization
static public function canSeeOtherUserRoles(Model $user_parent, Model $user_child)
{
return self::roleIsParentOfDirectChild($user_parent, $user_child);
}
static public function canShowGroup(array $parent_group, string $child_group)
{
$groupsHelper = new GroupsHelper();
foreach ($parent_group as $group) {
if (in_array($child_group, config('roles.roles'))) {
return true;
}
}
abort(403);
}
Result :
There was 1 error:
1) ::testCanSeeOtherUserRoles
ReflectionException: Class config does not exist

Improving MVP in Scala

The classical strongly typed MVP pattern looks like this in Scala:
trait IView { }
trait Presenter[View <: IView] { // or have it as an abstract type member
val view : View
}
case class View1(...) extends IView { ... }
case object Presenter1 extends Presenter[View1] {
val view = View1(...)
}
Now, I wonder if there is any nice way to improve on it which I am missing...
Nice thing about MVP pattern is that it makes your UI code unit testable.
I'd suggest you to avoid instantiating view in presenter and pass it to constructor.
That will allow you to just mock out the View and unit test the Presenter.
Replace you code
case object Presenter1 extends Presenter[View1] {
val view = View1(...)
}
with
case object Presenter1(val view: View1) extends Presenter[View1] {
...
}

Resources