Extend Parse SDK Object in TypeScript - parse-platform

In order to define easy getters and setters for Parse objects in angular2, I want to extend Parse.Object like so:
const Parse = require('parse').Parse;
export class Test extends Parse.Object {
constructor() {
super('Test');
}
get items():Array<string> {
return super.get('items');
}
set items(value:Array<string>) {
super.set('items', value);
}
}
Parse.Object.registerSubclass('Test', Test);
However, I get the following error:
error TS2507: Type 'any' is not a constructor function type.

Related

Enforce return value type for GraphQL resolvers in NestJS

Is there a way to enforce the return value of a #Query function inside resolvers? Given the code below:
#Resolver(() => Project)
export class ProjectResolver {
constructor(private projectService: ProjectService) {}
#Query(() => [ProjectFull])
async projects() {
// return anything
}
}
projects method can return anything w/o Typescript complaining. We could annotate the method with a return type (even enforce this annotation using eslint), but it won't be attached to the return type of a query.

When I create a template object to be used inside my Xamarin Forms code, is there a way I can use C# fluent with Build to create the template?

I have a template class that is in its own namespace and that I add to my code with `
new InfoLabel()`{ Text = "abc" };
Note that this is just a very simple example and I have other template objects that don't just depend on one thing, for example an object with 2-3 labels.
Is there a way that I can apply Xamarin C# fluent to create a templated object?
Here is the simple example object that I have:
namespace Test
{
public class InfoLabel : Label
{
public InfoLabel()
{
SetDynamicResource(FontFamilyProperty, Const.Fonts.DefaultRegular);
SetDynamicResource(FontSizeProperty, Const.Fonts.InfoTextFontSize);
SetDynamicResource(TextColorProperty, Const.Colors.InfoLabelColor);
LineBreakMode = LineBreakMode.WordWrap;
VerticalOptions = LayoutOptions.Start;
HorizontalTextAlignment = TextAlignment.Start;
}
}
}
What I would like to know is how I can set up the same thing using the latest C# fluent standards?
Here is the way I think it might be done. I used a Build() method but I would appreciate if someone more skilled than me could tell me if I am doing it correctly as this is a big change from what I am used to:
namespace Test
{
public class InfoLabel
{
public InfoLabel()
{
Build();
}
void Build() =>
new Label
{
LineBreakMode = LineBreakMode.WordWrap,
}
.TextLeft()
.DynamicResources((Label.FontFamilyProperty, Const.Fonts.DefaultRegular),
(Label.FontSizeProperty, Const.Fonts.InfoTextFontSize),
(Label.TextColorProperty, Const.Colors.InfoLabelColor));
Here is another idea that I have:
namespace Test
{
public class InfoLabel : Label
{
public InfoLabel()
{
LineBreakMode = LineBreakMode.WordWrap;
Build();
}
void Build() =>
this.TextLeft()
.DynamicResources((Label.FontFamilyProperty, Const.Fonts.DefaultRegular),
(Label.FontSizeProperty, Const.Fonts.InfoTextFontSize),
(Label.TextColorProperty, Const.Colors.InfoLabelColor));
Note that I am using an extension method for the resources.
You could create the instance of label like following
public class InfoLabel : Label
{
static InfoLabel CreateDefaultLabel()
{
return new InfoLabel
{
LineBreakMode = LineBreakMode.WordWrap,
}
.TextLeft()
.DynamicResources((Label.FontFamilyProperty, Const.Fonts.DefaultRegular),
(Label.FontSizeProperty, Const.Fonts.InfoTextFontSize),
(Label.TextColorProperty, Const.Colors.InfoLabelColor));
}
}
var label = InfoLabel.CreateDefaultLabel();
For more details of the usage of markup you could check this blog .

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

Can XUnit handle tests handle class and decimal parameters in the same method?

I have a test method with the following signature:
public void TheBigTest(MyClass data, decimal result)
{
And I'd like to run this in XUnit 2.1. I've got my CalculationData class all set up and that works if I remove the second parameter. But when I try to pass in the expected result as a second parameter by doing:
[Theory, ClassData(typeof(CalculationData)), InlineData(8893)]
It doesn't work. The test fails with a:
The test method expected 2 parameter values, but 1 parameter value was
provided.
Any ideas?
The class specified in the ClassData attribute needs to be an enumerable class that returns all of the parameters for the test method, not just the first one.
So, in your example, you would need something like:
public class CalculationData : IEnumerable<object[]>
{
IEnumerable<object[]> parameters = new List<object[]>()
{
new object[] { new MyClass(), 8893.0m },
new object[] { new MyClass(), 1234.0m },
// ... other data...
};
public IEnumerator<object[]> GetEnumerator()
{
return parameters.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
You can then add parameters to your MyClass class to enhance your test data.

how to unit test controller when automapper is used?

here's my controller
[POST("signup")]
public virtual ActionResult Signup(UserRegisterViewModel user)
{
if (ModelState.IsValid)
{
var newUser = Mapper.Map<UserRegisterViewModel, User>(user);
var confirmation = _userService.AddUser(newUser);
if (confirmation.WasSuccessful)
return RedirectToAction(MVC.Home.Index());
else
ModelState.AddModelError("Email", confirmation.Message);
}
return View(user);
}
here's my unit test:
[Test]
public void Signup_Action_When_The_User_Model_Is_Valid_Returns_RedirectToRouteResult()
{
// Arrange
const string expectedRouteName = "~/Views/Home/Index.cshtml";
var registeredUser = new UserRegisterViewModel { Email = "newuser#test.com", Password = "123456789".Hash()};
var confirmation = new ActionConfirmation<User>
{
WasSuccessful = true,
Message = "",
Value = new User()
};
_userService.Setup(r => r.AddUser(new User())).Returns(confirmation);
_accountController = new AccountController(_userService.Object);
// Act
var result = _accountController.Signup(registeredUser) as RedirectToRouteResult;
// Assert
Assert.IsNotNull(result, "Should have returned a RedirectToRouteResult");
Assert.AreEqual(expectedRouteName, result.RouteName, "Route name should be {0}", expectedRouteName);
}
Unit test failed right here.
var result = _accountController.Signup(registeredUser) as RedirectToRouteResult;
when I debug my unit test, I got following error message: "Missing type map configuration or unsupported mapping."
I think its because configuration is in web project, not the unit test project. what should I do to fix it?
You need to have the mapper configured, so in your test class set up, not the per-test setup, call the code to set up the mappings. Note, you'll also probably need to modify your expectation for the user service call as the arguments won't match, i.e, they are different objects. Probably you want a test that checks if the properties of the object match those of the model being passed to the method.
You should really use an interface for the mapping engine so that you can mock it rather than using AutoMapper otherwise it is an integration test not a unit test.
AutoMapper has an interface called IMappingEngine that you can inject into your controller using your IoC container like below (this example is using StructureMap).
class MyRegistry : Registry
{
public MyRegistry()
{
For<IMyRepository>().Use<MyRepository>();
For<ILogger>().Use<Logger>();
Mapper.AddProfile(new AutoMapperProfile());
For<IMappingEngine>().Use(() => Mapper.Engine);
}
}
You will then be able to use dependency injection to inject AutoMapper's mapping engine into your controller, allowing you to reference your mappings like below:
[POST("signup")]
public virtual ActionResult Signup(UserRegisterViewModel user)
{
if (ModelState.IsValid)
{
var newUser = this.mappingEngine.Map<UserRegisterViewModel, User>(user);
var confirmation = _userService.AddUser(newUser);
if (confirmation.WasSuccessful)
return RedirectToAction(MVC.Home.Index());
else
ModelState.AddModelError("Email", confirmation.Message);
}
return View(user);
}
You can read more about this here: How to inject AutoMapper IMappingEngine with StructureMap
Probably it is cool to abstract mapping into MappingEngine.
Sometimes I use following approach to IOC Automapper
In IOC builder:
builder.RegisterInstance(AutoMapperConfiguration.GetAutoMapper()).As<IMapper>();
where GetAutoMapper is:
public class AutoMapperConfiguration
{
public static IMapper GetAutoMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<OrderModelMapperProfile>();
cfg.AddProfile<OtherModelMapperProfile>();
//etc;
});
var mapper = config.CreateMapper();
return mapper;
}
}
And finally in Controller ctor
public MyController(IMapper mapper)
{
_mapper = mapper;
}

Resources