AdonisJs: Using Hashids - node.js

Had already someone used Hashids in AdonisJs?
Being more specific, in a Model, to return a property hashid in an object
I'm working on a migration from Laravel to Adonis.
In Laravel, it's possible just with a couple of code lines in each Model, like this:
use Hashids;
class Menu extends Model
{
use \OwenIt\Auditing\Auditable;
protected $appends = ['hashid'];
public function getHashidAttribute()
{
return Hashids::encode($this->attributes['id']);
}
}
I installed this NPM package: https://www.npmjs.com/package/adonis-hashids, and I tried to figure out how to use like the Laravel way

I'd used Computed Properties (https://adonisjs.com/docs/4.1/database-getters-setters#_computed_properties)
class Menu extends Model {
static get computed () {
return ['hashids']
}
getHashids({ id }) {
return Hashids.encode(id)
}
}

Related

What is the right way to export the class to be extended from other classes NodeJs?

Base class looks like this:
class BaseReport {
constructor(reportName) {
this.reportName = reportName;
}
async generateReport(accountId, request) {
let results = await this.getDataFromDb(request);
results = this.formatResults(results);
return updatedResults;
}
formatResults(data) {
//Some logig here
return result
}
getDataFromDb(request) {
//Logic to get data from database
return errorRequest;
}
}
module.exports = BaseReport;
The I have another class that extends Base class:
const BaseReport = require("./base.service");
class DataReport extends BaseReport {
constructor() {
super('dataReport');
}
formatResults(data) {
//Logic to format results in a different way
return data;
}
}
module.exports = new DataReport();
So far everything works well. DataReport class doesn't need to implement the method getDataFromDB because it is inherited from BaseReport class.
The problem starts when I am writing unit/integration tests.
When I try to stub function getData() it is not working (it is not being stubbed but instead it is calling the method and making the database call.
I understand WHY is happening... In BaseReport class I am exporting the class itself. So when I create an object on my unit tests and try to stub the function, that is not the same method and object which is initialized when the application is running. Every time you use the keyword "new" creates a new object and has its own methods.
If I want to stub a method from DataReport class it works fine because in there I am exporting an object of that class (module.exports = new DataReport();). In this case, it can only exist one copy of the object and so only one copy of the methods as well.
Now I can not do the same for BaseReport class because my understanding is that you CAN NOT extend BaseReport class if I exported a new object (module.exports = new BaseReport();).
What is the proper way to implement this in order to also have the unit tests working??

Get result of function in Laravel and add to another controller

I have this 1st controller.
class ValidatePassController extends Controller
{
protected function doShow(Post $post, Hash $hash)
{
return view('auth.cab.pcab');
}
}
I need to add if view was returned or something like that in the controller below.
class EditController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function xuibomja()
{
if (// in past controller view was returned))
{
return ('stassik');
}
return ('not stassik');
}
}
Any ideas? I have tried to set some vars, but it didn't work, so im out of ideas. Btw can't summary controllers to each other, codes needs to be in different controllers.
It's not the best practice to have a controller to call another controller.
what I recommend you to do is to create a class and move the functionality there, and create a facade to map to this class, and set both controllers to use that common functionality

Use interface to convert collection of objects with extensions and lambdas

I have some objects like user, address and so on, and Im converting them to business objects using extension methods:
public static UserModel ToPresentationForm(this User pUser)
{
return new UserModel
{
...
map data
...
};
}
Also I need to convert strongly typed collections and usually I have the following code:
public static List<UserModel> ToPresentationForm(this List<User> pUserColl)
{
return pUserColl.Select(x => x.ToPresentationForm()).ToList();
}
I was thinking, what if I add some interface, like IPresentationForms and will be able to use it, to write method like
public static List<T> ToPresentationForm(this List<IPresentationForms> pTemplate)
{
return pUserColl.Select(x => x.ToPresentationForm()).ToList();
}
Not sure how to provide parameter to method type to make it generic. So the actual question is, how to do that.
P.S. Im using C# 4.0
Unfortunately since there is likely no relationship between User and UserModel, there is no way to create an interface to do what you want.
On the other hand, let's say that User and UserModel both implement the IUser interface. Then you could have an interface like this:
interface IPresentationForms<T>
{
T ToPresentationForm();
}
And you could define User like this:
class User: IUser, IPresentationForms<IUser>
{
public IUser ToPresentationForm()
{
return new UserModel(...);
}
.... // implement IUser
}
That could enable you to define ToPresentationForm something like this:
public static List<T> ToPresentationForm<T>(this IEnumerable<T> pTemplate)
where T : IPresentationForms<T>
{
return pTemplate.Select(x => x.ToPresentationForm()).ToList();
}
That's a lot of work to do to avoid a few extra methods.

ViewHelper newable/injectable dilemma

I'm trying to design an application following Misko Heverys insights. It's an interesting experiment and a challenge. Currently I'm struggling with my ViewHelper implementation.
The ViewHelper decouples the model from the view. In my implementation it wraps the model and provides the API for the view to use. I'm using PHP, but I hope the implementation is readable for everyone:
class PostViewHelper {
private $postModel;
public function __construct(PostModel $postModel) {
$this->postModel = $postModel;
}
public function title() {
return $this->postModel->getTitle();
}
}
In my template (view) file this could be called like this:
<h1><?php echo $this->post->title(); ?></h1>
So far so good. The problem I have is when I want to attach a filter to the ViewHelpers. I want to have plugins that filter the output of the title() call. The method would become like this:
public function title() {
return $this->filter($this->postModel->getTitle());
}
I need to get observers in there, or an EventHandler, or whatever service (in what I see as a newable, so it needs to be passed in through the stack). How can I do this following the principles of Misko Hevery? I know how I can do this without it. I'm interested in how for I can take it and currently I don't see a solution. ViewHelper could be an injectable too, but then getting the model in there is the problem.
I didn't find the blog post you referenced very interesting or insightful.
What you are describing seems more like a Decorator than anything to do with dependency injection. Dependency injection is how you construct your object graphs, not their state once constructed.
That said, I'd suggest taking your Decorator pattern and running with it.
interface PostInterface
{
public function title();
}
class PostModel implements PostInterface
{
public function title()
{
return $this->title;
}
}
class PostViewHelper implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->post->title();
}
}
class PostFilter implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->filter($this->post->title());
}
protected function filter($str)
{
return "FILTERED:$str";
}
}
You'd simply use whatever DI framework you have to build this object graph like so:
$post = new PostFilter(new PostViewHelper($model)));
I often use this approach when building complex nested objects.
One problem you might run into is defining "too many" functions in your PostInterface. It can be a pain to have to implement these in every decorator class. I take advantage of the PHP magic functions to get around this.
interface PostInterface
{
/**
* Minimal interface. This is the accessor
* for the unique ID of this Post.
*/
public function getId();
}
class SomeDecoratedPost implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->_post = $post;
}
public function getId()
{
return $this->_post->getId();
}
/**
* The following magic functions proxy all
* calls back to the decorated Post
*/
public function __call($name, $arguments)
{
return call_user_func_array(array($this->_post, $name), $arguments);
}
public function __get($name)
{
return $this->_post->get($name);
}
public function __set($name, $value)
{
$this->_post->__set($name, $value);
}
public function __isset($name)
{
return $this->_post->__isset($name);
}
public function __unset($name)
{
$this->_post->__unset($name);
}
}
With this type of decorator in use, I can selectively override whatever method I need to provide the decorated functionality. Anything I don't override is passed back to the underlying object. Multiple decorations can occur all while maintaining the interface of the underlying object.

Subsonic 3, how to CRUD using LinqTemplates?

I am new to Subsonic, and it seems that I cant find out a natural way to do CRUD operations using the LINQ template classes. I guess in ActiveRecord, you could:
Product p = new Product();
p.ProductCode = "xxx";
p.Add();
Using the LINQTemplate generated classes however, how can I do the same thing? I can only use something like this below to insert a product object:
db.Insert.Into<UnleashedSaaS.PRODUCT>(prod => prod.Code, prod => prod.Description).Values("Product1", "Product1 Desc").Execute();
Who could kindly give me some hints? I'd really appreciate it.
All the CRUD happens in SubSonicRepository, which you can derive from. For example, I would have a class like this:
public class ProductRepository : SubSonicRepository<Product> {
public ProductRepository() : base(new NorthwindDB()) { }
// need this here because base doesn't expose the DB class that I know of
protected NorthwindDB _db;
protected NorthwindDB DB {
get {
if (_db == null) _db = new NorthwindDB();
return _db;
}
}
public void Save(Product product) {
if (product.ProductId == 0) {
Add(product); // Add is part of SubSonicRepository
} else {
Update(product);
}
}
public void Delete(Product product) { ... }
public List<Product> ListAll() {
var products = from p in DB.Products
select p;
return products.ToList();
}
public Product GetById(int id) {
return DB.GetByKey(id);
}
}
And so on. It's nice because you can consolidate all your data access methods in one place. If you have Sprocs, they're generated as methods on DB as well.
When I get time I'm going to work on adding a Save method to SubSonicRepository directly so you don't have to do the check yourself to see which method (Add or Update) to call.
I have modified the Classes.tt file to include:
public partial class <#=tbl.ClassName#>Repository : SubSonicRepository<<#=tbl.ClassName#>>
{
public <#=tbl.ClassName#>Repository() : base(new <#=DatabaseName#>DB()) { }
}
Insert that bunch of lines between
<# foreach(Table tbl in tables){#>
and
/// <summary>
right at the top, near the namespace declaration, in my file it can be inserted in line 18.
The last thing to do is to add another "using" statement, in line 10, the next line after System.Linq statement. Now it should look like:
using System.Linq;
using SubSonic.Repository;
That will generate a repository to give you access to basic functionality, but can be modified in another partial class.
Hope that helps.

Resources