Express API Refkit

Posted on Leave a comment

https://github.com/anuragbhd/express-api-refkit

I frequently create APIs for muse/professional apps, and every time I find myself scrambling to pick the best pieces from my previously built APIs or online repositories.

To streamline this, I recently created this reference kit (mostly for myself) to help me in writing a production-grade Express-based API from scratch. Sharing with this group in hopes that my fellow XTians will benefit from it when writing their own RESTful APIs.

As noted in the docs:

This is NOT a starter template. The purpose of this repository is to provide reference code to anyone looking to create a beautiful, secure and well-tested Node/Express-based API from scratch.

Creating from scratch has the invaluable benefit of learning while doing. Most likely, there will be struggle which will make you better. You will know by heart all parts under the hood and exactly how they interact with each other. Basing your project off of a starter kit takes that away from you. Hence the need for a reference kit (or refkit, as I like to call it).

If you are experienced in Express, feel free to open pull requests to add improvements.

Contributions in any form are welcome 💁‍♂️

Featured image credit Nick Youngson CC BY-SA 3.0 Alpha Stock Images

Flutter: Design to app like a pro

Posted on Leave a comment

Sharing with ya’ll the recording of my session from Sapient’s April 11 Flutter meetup.

Warning: This is a longish session (48 mins). Watch at your discretion. You have been warned.
(I really need to work on my time-boxing skills)

Do also see the other 🆒 sessions in this playlist:
https://www.youtube.com/playlist?list=PLfZqxzeCGmPUWopRNcf86Kmusrog73yhL

Use Flutter’s FutureBuilder with care

Posted on Leave a comment

I learned this the hard way. I knew Flutter’s stateless and stateful widget lifecycles well. But I was ignorant.

I made a grave, mostly fatal, mistake of doing something like this:

FutureBuilder<List<Product>>(
  future: this.productRepo.getProducts(),
  builder: (context, snapshot) {
    ...
)

class ApiProductRepo implements ProductRepo {
  Future<List<Product>> getProducts() async {
    // Call an API to get products
    // Return products
  }
}

Do you see the graveness of my code? No? Check again, I’ll wait.

Okay. Maybe you’ve guessed it, maybe not. See the code below. This is the culprit:

future: this.productRepo.getProducts()

FutureBuilder’s official docs say:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder’s parent is rebuilt, the asynchronous task will be restarted.

A general guideline is to assume that every build method could get called every frame, and to treat omitted calls as an optimization.

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

Commit the bolded line in memory. For like ever. Otherwise, you’ll end up in the same trap as I. Flutter makes app development so seamless and fun that at times you forget basic optimizations. In my case, I was using a third-party metered API and found myself hitting close to my daily quotas 4x sooner than anticipated. That’s because FutureBuilder was calling the API 4 times, once on each widget rebuild.

My fix was simple: convert my stateless widget to a stateful one and cache API response in state.

class ProductListScreen extends StatefulWidget {
  static const id = 'product_list';

  @override
  _ProductListScreenState createState() => _ProductListScreenState();
}

class _ProductListScreenState extends State<ProductListScreen> {
  List<Product> products;

  /// Returns recipes in cache-first fashion.
  Future<List<Product>> _getProducts() async {
    if (this.products != null) {
      return this.products;
    }

    final productRepo = Provider.of<ProductRepository>(context);
    this.products = await productRepo.getProducts();
    return this.products;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Recipe>>(
        future: this._getProducts(),
        builder: (context, snapshot) {
          ...
        },
      ),
    );
  }
}

Follow this advice, and save tonnes of troubles later.

Mocking Firestore in Flutter

Posted on 2 Comments

I have been writing unit tests like crazy for my muse Flutter app, in my own TDD-like fashion. Writing meaningful tests and watch them go from red to green is a great feeling for real. If you aren’t doing that yet, I highly recommended.

Flutter comes with an excellent testing library called — wait a minute — test. It has one of the most comprehensive set of assertion matchers I have ever seen.

  • Want to test a type? Check.
  • Want to test a future? Check.
  • Want to test an error emitted by a stream? Check.
  • Want to test if your method accidentally rings your neighbor’s door? Umm, well, you gotta do it yourself.

A lot of times you will need to create mocks to avoid side effects in your production database or APIs. Mockito is an awesome package for that. While Mockito works great for general-purpose mocking, I found cloud_firestore_mocks to be closer to the real deal in my testing.

I have used it so extensively in my own tests that I found myself wanting for more. cloud_firestore_mocks, as awesome as it is, does not yet support 100% of Firestore’s APIs. For example, it does not yet support arrayContainsAny where query clause. Same is true for startAt and endAt.

I wanted it so much that I implemented it myself and sent a pull request to Ahn, cloud_firestore_mocks original author. The PR has been merged and the change will land on pub.dev soon. More power to open source!

If you are using Firestore with Flutter, check out cloud_firestore_mocks today and save yourself shit loads of time troubleshooting bugs later. Highly recommended.

A joke only Flutter developers would understand

Posted on Leave a comment

Developer: “YESSS! My world-class widget test is ready to run.”

(runs the test)

Debug Console: “Expected to see 1 widget, found none.”

Developer: What! Why, why, why!!!

(figures out all async calls in the widget; spends 4 hours re-reading about widget testing, exploring the source code of WidgetTester.pump() and setting up mock classes using Mockito.)

Developer: “Muwaha haha! I am the greatest mocker ever lived.”

(runs the test again)

Debug Console: “A RenderFlex overflowed by 20 pixels on the right.”