<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Andongwisye Mwamengo</title>
    <description>The latest articles on DEV Community by Andongwisye Mwamengo (@andymwamengo).</description>
    <link>https://dev.to/andymwamengo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F805070%2Fc17b3b37-a407-4472-ac9f-562ca36ed9cd.jpg</url>
      <title>DEV Community: Andongwisye Mwamengo</title>
      <link>https://dev.to/andymwamengo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/andymwamengo"/>
    <language>en</language>
    <item>
      <title>Flutter how to override System Status bar and protect App from screenshots in Android/iOS</title>
      <dc:creator>Andongwisye Mwamengo</dc:creator>
      <pubDate>Tue, 03 Sep 2024 18:48:04 +0000</pubDate>
      <link>https://dev.to/andymwamengo/flutter-how-to-override-system-status-bar-and-protect-app-from-screenshots-in-androidios-102f</link>
      <guid>https://dev.to/andymwamengo/flutter-how-to-override-system-status-bar-and-protect-app-from-screenshots-in-androidios-102f</guid>
      <description>&lt;p&gt;When developing mobile applications, ensuring that sensitive information displayed on the screen is protected from unauthorized screenshots or screen recordings can be critical. Flutter provides the flexibility to achieve this across both Android and iOS platforms. Below, we'll walk through how to override the system status bar and implement screenshot protection in a Flutter app.&lt;/p&gt;

&lt;p&gt;First, ensure your Flutter project is set up with the necessary dependencies. In this example, we'll focus on two key tasks:&lt;/p&gt;

&lt;p&gt;Overriding the System Status Bar: Customizing the appearance of the status bar and navigation bar.&lt;br&gt;
Protecting the App from Screenshots: Ensuring sensitive content is not captured in screenshots or screen recordings.&lt;/p&gt;

&lt;p&gt;Overriding the System Status Bar in Flutter&lt;br&gt;
In &lt;code&gt;main.dart&lt;/code&gt;, we will create a simple app that customizes the system UI overlays.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() =&amp;gt; runApp(const SystemOverlayStyleApp());

class SystemOverlayStyleApp extends StatelessWidget {
  const SystemOverlayStyleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
        brightness: Brightness.light,
      ),
      home: const SystemOverlayPage(),
    );
  }
}

class SystemOverlayPage extends StatefulWidget {
  const SystemOverlayPage({super.key});

  @override
  State&amp;lt;SystemOverlayPage&amp;gt; createState() =&amp;gt; _SystemOverlayPageState();
}

class _SystemOverlayPageState extends State&amp;lt;SystemOverlayPage&amp;gt;
    with WidgetsBindingObserver {
  bool _isMinimized = false;
  final color = Colors.blue;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      if (state == AppLifecycleState.inactive ||
          state == AppLifecycleState.paused) {
        _isMinimized = true;
      } else if (state == AppLifecycleState.resumed) {
        _isMinimized = false;
      }
    });
  }

  SystemUiOverlayStyle _currentStyle = SystemUiOverlayStyle.dark.copyWith(
    statusBarColor: Colors.blue,
    systemNavigationBarColor: Colors.blue,
  );

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion&amp;lt;SystemUiOverlayStyle&amp;gt;(
      value: _currentStyle,
      child: _isMinimized == true
          ? Container(
              color: Colors.grey,
            )
          : Scaffold(
              appBar: AppBar(
                backgroundColor: Colors.red,
                automaticallyImplyLeading: true,
                title: Text('Post'),
              ),
              body: Container(
                color: Colors.amber,
                width: double.infinity,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: &amp;lt;Widget&amp;gt;[
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Text(
                        'Millions Using Dart Language',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                    ),
                  ],
                ),
              ),
              bottomNavigationBar: BottomAppBar(
                color: color.withOpacity(0.95),
                shape: const CircularNotchedRectangle(),
                notchMargin: 5.0,
                clipBehavior: Clip.antiAlias,
                child: SizedBox(
                  height: kBottomNavigationBarHeight,
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: &amp;lt;Widget&amp;gt;[
                      IconButton(
                        icon: const Icon(Icons.home),
                        onPressed: () {
                          setState(() {});
                        },
                      ),
                      IconButton(
                        icon: const Icon(Icons.search),
                        onPressed: () {
                          setState(() {});
                        },
                      ),
                      IconButton(
                        icon: const Icon(Icons.favorite_border_outlined),
                        onPressed: () {
                          setState(() {});
                        },
                      ),
                      IconButton(
                        icon: const Icon(Icons.account_circle_outlined),
                        onPressed: () {
                          setState(() {});
                        },
                      )
                    ],
                  ),
                ),
              ),
            ),
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Protecting the App from Screenshots on iOS&lt;br&gt;
To protect your Flutter app from screenshots on iOS, we need to override the &lt;code&gt;AppDelegate.swift&lt;/code&gt; file. This file handles the application's lifecycle events in iOS. The goal is to prevent screen capture by using secure layers over the app's window.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import UIKit
import Flutter
import Foundation

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -&amp;gt; Bool {
    self.window.makeSecure()
    GeneratedPluginRegistrant.register(with: self)
    self.window?.layer.contents = nil
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

extension UIWindow {
    func makeSecure() {
        let field = UITextField()
        let view = UIView(frame: CGRect(x: 0, y: 0, width: field.frame.width, height: field.frame.height))
        let image = UIImageView(image: UIImage(named: "whiteImage"))
        image.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        field.isSecureTextEntry = true
        if let window = self as UIWindow? {
            window.addSubview(field)
            view.addSubview(image)
            window.layer.superlayer?.addSublayer(field.layer)
            if let lastLayer = field.layer.sublayers?.last {
                lastLayer.addSublayer(window.layer)
            }
            field.leftView = view
            field.leftViewMode = .always
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Protecting the App from Screenshots on Android&lt;br&gt;
For Android, we implement screenshot protection by using a flag in the &lt;code&gt;MainActivity.kt&lt;/code&gt; file. This file is responsible for configuring the Flutter engine for Android.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import android.view.WindowManager.LayoutParams

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        window.addFlags(LayoutParams.FLAG_SECURE)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Summary&lt;br&gt;
This guide covered how to customize the system status bar in a Flutter application and protect your app from screenshots or screen recordings on both Android and iOS platforms.&lt;/p&gt;

&lt;p&gt;For Flutter: We used SystemUiOverlayStyle to manage the appearance of the system status bar.&lt;br&gt;
For iOS: We added a secure layer over the app window using Swift, making it impossible for the system to capture the screen.&lt;/p&gt;

&lt;p&gt;For Android: We utilized the FLAG_SECURE flag to prevent screenshots or screen recordings.&lt;br&gt;
By implementing these techniques, you can enhance the security of your Flutter application and ensure that sensitive data remains protected.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to create and generate migrations in Typeorm 0.3+ with NestJS 9+</title>
      <dc:creator>Andongwisye Mwamengo</dc:creator>
      <pubDate>Tue, 10 Oct 2023 06:17:34 +0000</pubDate>
      <link>https://dev.to/andymwamengo/how-to-create-and-generate-migrations-in-typeorm-03-with-nestjs-9-4g55</link>
      <guid>https://dev.to/andymwamengo/how-to-create-and-generate-migrations-in-typeorm-03-with-nestjs-9-4g55</guid>
      <description>&lt;p&gt;Migration from Typeorm 0.2 to 0.3 has made changes in how to connect to the database and run migrations due to the fact that they deprecated ormconfig.json but you have to use dataSource which will hold the database connection.&lt;/p&gt;

&lt;p&gt;so today I'll show you how to write generate and run migrations in NestJS 9+ with Typeorm 0.3+ with sample code.&lt;/p&gt;

&lt;p&gt;First of all install the latest version of nestjs-cli, ts-node,  typeorm, and your database like Postgres, MySQL with the following commands&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm i -g @nestjs/cli 
$ npm i -g typeorm
$ npm i -g ts-node
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a project or in your existing project configure database connections and create entities for your database.&lt;/p&gt;

&lt;p&gt;Let's get started by creating a dataSource.ts file in your project&lt;br&gt;
 dataSource.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as dotenv from 'dotenv';
dotenv.config();
import { DataSource } from 'typeorm';

export default new DataSource({
  type: 'postgres',
  host: process.env.DATABASE_HOST,
  port: +process.env.DATABASE_PORT,
  username: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_DB,
  synchronize: false,
  dropSchema: false,
  logging: false,
  logger: 'file',
  entities: ['dist/**/*.entity{.ts,.js}'],
  migrations: ['src/migrations/**/*.ts'],
  subscribers: ['src/subscriber/**/*.ts'],
  migrationsTableName: 'migration_table',
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the following code to your app.module.ts file with the following code&lt;br&gt;
app.module.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) =&amp;gt; ({
        type: 'postgres',
        host: configService.get('DATABASE_HOST'),
        port: configService.get('DATABASE_PORT'),
        username: configService.get('DATABASE_USER'),
        password: configService.get('DATABASE_PASSWORD'),
        database: configService.get('DATABASE_DB'),
        entities: ['dist/**/*.entity{.ts,.js}'],
        synchronize: false,
        autoLoadEntities: true,
        migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
        seeds: [__dirname + '/seeds/**/*{.ts,.js}'],
        factories: [__dirname + '/factories/**/*{.ts,.js}'],
        cli: {
          migrationsDir: __dirname + '/migrations/',
        },
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [],
})
export class AppModule {}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Update the package.json to include the following migrations commands&lt;br&gt;
package.json&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; "scripts": {
    ....
    "typeorm": "typeorm-ts-node-commonjs",
    "schema:sync": "npx typeorm-ts-node-commonjs schema:sync",
    "typeorm:cache": "npx typeorm-ts-node-commonjs cache:clear",
    "schema:drop": "npx typeorm-ts-node-commonjs -d ./src/database/data-source.ts",
    "migration:create": "typeorm migration:create ./src/migrations/schema-update",
    "migration:generate": "npx typeorm-ts-node-commonjs migration:generate ./src/migrations/schema-update -d ./src/database/data-source.ts",
    "migration:show": "npx typeorm-ts-node-commonjs migration:show -d ./src/database/data-source.ts",
    "migration:run": "npx typeorm-ts-node-commonjs migration:run -d  ./src/database/data-source.ts",
    "migration:revert": "npx typeorm-ts-node-commonjs migration:revert -d ./src/database/data-source.ts"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you are done with the setup above you can run the following commands in your project root&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;npm run migration:create&lt;/code&gt; This will create an empty migration file where you can write your SQL in both UP and Down functions to either schema drop or create the schema.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;npm run migration:generate&lt;/code&gt; This will generate SQL from your entities and you can find them inside migrations folder as per data-source.ts configuration.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;npm run migration:run&lt;/code&gt; This will populate your database with the new database schema as per the migration file generated in 2, Now you have updated your database schema.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note: Make sure you set synchronize: false in the production project otherwise if there a schema changes in your code, you might lose data in your existing database.&lt;/p&gt;

&lt;p&gt;Feel free to check typeorm &lt;a href="//typeorm.io"&gt;typeorm.io&lt;/a&gt; and nestjs docs &lt;a href="https://docs.nestjs.com/"&gt;https://docs.nestjs.com/&lt;/a&gt;, for more information.&lt;/p&gt;

&lt;p&gt;I want to give you one reason why we have dataSource.ts database configurations and why we have another database connection inside app.module.ts?. &lt;br&gt;
&lt;code&gt;Migration runs without NestJS runtime. NestJS will use app.module.ts database connection and migration will use dataSource.ts&lt;/code&gt;&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>typescript</category>
      <category>typeorm</category>
    </item>
    <item>
      <title>How to write a Data Seeder Helper in NestJS 9+ with Typeorm 0.3+</title>
      <dc:creator>Andongwisye Mwamengo</dc:creator>
      <pubDate>Tue, 16 May 2023 04:52:14 +0000</pubDate>
      <link>https://dev.to/andymwamengo/how-to-write-a-data-seeder-helper-in-nestjs-9-with-typeorm-03-239k</link>
      <guid>https://dev.to/andymwamengo/how-to-write-a-data-seeder-helper-in-nestjs-9-with-typeorm-03-239k</guid>
      <description>&lt;p&gt;I have been looking for different solutions that can help how to seed data inside database using a helper function without using any third part package.&lt;/p&gt;

&lt;p&gt;After struggling with different methods and solutions then I come up with this solutions. It works fine without any third part package.&lt;/p&gt;

&lt;p&gt;Let's dive deep into code&lt;br&gt;
Assuming you generated your application with NestJS CLI 9 &lt;/p&gt;

&lt;p&gt;Your App module will look like below&lt;br&gt;
&lt;code&gt;app.module.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
      entities: ['dist/**/*.entity{.ts,.js}'],
      synchronize: true,
      autoLoadEntities: true,
    }),
  ],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then create a seeder helper function like this below, Feel free to add more data as you want.&lt;br&gt;
&lt;code&gt;seed-data.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DataSource, In } from 'typeorm';
import { Permission } from '../../modules/permissions/entities/permission.entity';
import { Role } from '../../modules/permissions/entities/role.entity';
import { Auth } from '../../modules/users/entities/auth.entity';
import { PERMISSIONS_LIST } from './data/permissions.seeders';
import { ROLE_LIST } from './data/roles.seeders';

export async function seedData(dataSource: DataSource): Promise&amp;lt;void&amp;gt; {

  const permissionRepository = dataSource.getRepository(Permission);
  const roleRepository = dataSource.getRepository(Role);

  const permissionsList = PERMISSIONS_LIST;
  for (const permission of permissionsList) {
    let _permission = permissionRepository.create(
      permission as unknown as Permission,
    );
    await permissionRepository.save(_permission);
  }

  const rolesList = ROLE_LIST;
  for (const role of rolesList) {
    let _permissions = await permissionRepository.findBy({
      id: In(role.permissions),
    });
    let _roleItem = {
      name: role.name,
      guard: role.guard,
      code: role.code,
    };
    let _role = roleRepository.create({
      ..._roleItem,
      permissions: _permissions,
    });
    await roleRepository.save(_role);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that ROLE_LIST and PERMISSION_LIST are sample data in an array format like&lt;br&gt;
&lt;code&gt;data.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { GuardType } from "src/modules/permissions/entities/guard-type.enum";

export const ROLE_LIST = [
  {
    name: "admin",
    guard: GuardType.ADMIN,
    code: "admin",
    permissions: [1, 2]
  },
  {
    name: "user",
    guard: GuardType.USER,
    code: "user",
    permissions: [2]
  },
  {
    name: "test",
    guard: GuardType.TEST,
    code: "test",
    permissions: [2]
  }
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then write a helper function to boostrap your app using NestFactory function like below&lt;br&gt;
&lt;code&gt;seed.helper.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DataSource } from 'typeorm';
import { seedData } from './seed-data';
import { AppModule } from '../../app.module';
import { NestFactory } from '@nestjs/core';

async function runSeeder() {
  const app = await NestFactory.create(AppModule);
  const dataSource = app.get(DataSource);
  await seedData(dataSource);
  await app.close();
}
runSeeder();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then final add the command to package.json file so that you can execute a runSeeder function inside package.json.&lt;br&gt;
&lt;code&gt;package.json&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "build": "nest build",
    ...
    "data:sync": "ts-node -r tsconfig-paths/register ./src/seeders/seed.helper.ts"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now everything is now set just run &lt;code&gt;npm run data:sync&lt;/code&gt; now data should be populated in the database.&lt;/p&gt;

&lt;p&gt;Feel free to leave a comment in this post below.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to write a base service for your NestJS REST API using Typeorm Version 0.3+</title>
      <dc:creator>Andongwisye Mwamengo</dc:creator>
      <pubDate>Wed, 10 May 2023 18:44:00 +0000</pubDate>
      <link>https://dev.to/andymwamengo/how-to-write-a-base-service-for-your-nestjs-rest-api-using-typeorm-version-03-489f</link>
      <guid>https://dev.to/andymwamengo/how-to-write-a-base-service-for-your-nestjs-rest-api-using-typeorm-version-03-489f</guid>
      <description>&lt;p&gt;I have been looking for different ways of writing a base service in NestJS application for all shared database CRUD and others operations using Typeorm v0.3. I din't find any article relating to this case. Therefore I decided to write this blogpost.&lt;/p&gt;

&lt;p&gt;Migration from Typeorm v0.2 to v0.3 has brought alot of changes when writting some of the database queries. Feel free to check the migrations guide.&lt;/p&gt;

&lt;p&gt;We had a simple way of writing a base service for all CRUD operations in NestJS using typeorm in v0.2. Since typeorm introduced typeorm v0.3 there are couple of deprecations that happened such that you wont be able to use the approach from v0.2 of typeorm.&lt;/p&gt;

&lt;p&gt;Today I'll be showing you and writing code on how to implement base service for all crud operations and other shared methods that you want to share across your application.&lt;/p&gt;

&lt;p&gt;Let me start with the old way with typeorm v0.2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DeleteResult, Repository } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { HttpException, HttpStatus } from '@nestjs/common';

export class BaseService&amp;lt;T&amp;gt; {
  constructor(private readonly repository: Repository&amp;lt;T&amp;gt;) {}

  async findAll(): Promise&amp;lt;T[]&amp;gt; {
    return await this.repository.find();
  }

  async findOneById(id: FindOneOptions&amp;lt;T&amp;gt;): Promise&amp;lt;T&amp;gt; {
    return await this.repository.findOne({ where: { id } });
  }

  async create(data: DeepPartial&amp;lt;T&amp;gt; ) {
   return await this.repository.save(data);
  }

  async update(id: FindConditions&amp;lt;T&amp;gt;, partialEntity: QueryDeepPartialEntity&amp;lt;T&amp;gt;) {
   return await this.repository.update(id, partialEntity);
  }

  async delete(id: FindConditions&amp;lt;T&amp;gt;): Promise&amp;lt;DeleteResult&amp;gt; {
    return await this.repository.delete(id);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The below code show how to implement it with typeorm v0.3 using dataSource since the main changes we encounter is due to the fact that typeorm deprecated connection in v0.2 and added a dataSource to typeorm v0.3&lt;/p&gt;

&lt;p&gt;This is the first way of writing a base service&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DataSource, FindOneOptions, Repository } from 'typeorm';
import { EntityTarget } from 'typeorm/common/EntityTarget';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';

export class GenericRepository&amp;lt;T&amp;gt; extends Repository&amp;lt;T&amp;gt; {
  constructor(target: EntityTarget&amp;lt;T&amp;gt;, dataSource: DataSource) {
    super(target, dataSource.createEntityManager());
  }

  async findActive(options: FindOneOptions&amp;lt;T&amp;gt;): Promise&amp;lt;T[]&amp;gt; {
    return await this.find(options);
  }

  async findByEmail(options: FindOneOptions&amp;lt;T&amp;gt;): Promise&amp;lt;T&amp;gt; {
    return this.findOne(options);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use the above base service write the following code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@nestjs/common';
import { DataSource, EntityTarget } from 'typeorm';
import { User } from './user.entity';
import { BaseService } from './base.service';

@Injectable()
export class UserService extends BaseService&amp;lt;User&amp;gt; {
  constructor(
    @InjectRepository(DataSource)
    private readonly dataSource: DataSource,
  ) {
    super(dataSource, User);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also decide to write the code in the following style also.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Repository } from 'typeorm';
import { EntityTarget } from 'typeorm/common/EntityTarget';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';

export abstract class BaseService&amp;lt;T&amp;gt; {
  protected constructor(protected readonly repository: Repository&amp;lt;T&amp;gt;) {}

  async create(entity: T): Promise&amp;lt;T&amp;gt; {
    return await this.repository.save(entity);
  }

  async findOne(options: FindOneOptions&amp;lt;T&amp;gt;): Promise&amp;lt;T&amp;gt; {
    return this.repository.findOne(options);
  }

  async findAll(): Promise&amp;lt;T[]&amp;gt; {
    return this.repository.find();
  }

  async update(id: number, options: FindOneOptions&amp;lt;T&amp;gt;, entity: T): Promise&amp;lt;T&amp;gt; {
    await this.repository.update(id, entity as QueryDeepPartialEntity&amp;lt;T&amp;gt;);
    return this.findOne(options);
  }

  async delete(id: number): Promise&amp;lt;void&amp;gt; {
    await this.repository.delete(id);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use the above base service write the following code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { BaseService } from './base.service';

@Injectable()
export class UserService extends BaseService&amp;lt;User&amp;gt; {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository&amp;lt;User&amp;gt;,
  ) {
    super(userRepository);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Feel free to checkout migrations from Typeorm version 0.2 to 0.3 via &lt;a href="https://github.com/typeorm/typeorm/issues/9286"&gt;Migration guide from v0.2.x to v0.3.x · Issue&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;If you have any issue or comment feel free to leave it in this post.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
