<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yasir Aktunç on Medium]]></title>
        <description><![CDATA[Stories by Yasir Aktunç on Medium]]></description>
        <link>https://medium.com/@mhmtyasr?source=rss-be5fa846cd67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FvomRy5vdzJpk_y-li7n1Q.jpeg</url>
            <title>Stories by Yasir Aktunç on Medium</title>
            <link>https://medium.com/@mhmtyasr?source=rss-be5fa846cd67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:10:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mhmtyasr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Build a Multi-Layered Backend Architecture with SQLite in React Native?]]></title>
            <link>https://medium.com/@mhmtyasr/how-to-build-a-multi-layered-backend-architecture-with-sqlite-in-react-native-d3ec5dd7cc6e?source=rss-be5fa846cd67------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3ec5dd7cc6e</guid>
            <category><![CDATA[automapper]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <category><![CDATA[typeorm]]></category>
            <dc:creator><![CDATA[Yasir Aktunç]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 08:53:29 GMT</pubDate>
            <atom:updated>2025-02-21T08:53:29.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build a Multi-Layered Backend Architecture with SQLite in React Native? (Supports Windows, iOS, and Android)</h3><p>Hello, I’m Yasir Aktunç, a Web and React Native developer. Today, I will introduce the SQLite-based backend architecture that I use in my React Native TypeScript project. The key feature of this structure is its seamless compatibility with React Native Windows, Android, and iOS platforms.</p><h3>Why Do We Need an Architecture?</h3><p>The backend architecture used in mobile applications is often complex and can face compatibility issues across different platforms. My goal was to create a backend structure that is both <strong>efficient, modular, and easily testable</strong> while utilizing a lightweight database like SQLite. Below, you can see the general architecture of our backend system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*mE5nvWKnG-NLvHMYFd-Nuw.png" /></figure><h3>Technologies Used</h3><h3>SQLite3: Database</h3><p>SQLite3 is a lightweight and portable database used to perform database operations in React Native applications. It is commonly preferred for storage requirements and facilitates data reading, writing, updating, and deletion using SQL queries. SQLite is a serverless, file-based database that offers an efficient solution in terms of performance and resource usage for small-scale applications.</p><h3>Tsyringe: For a Modular Structure with Dependency Injection</h3><p><strong>T</strong>Tsyringe is a library used to implement dependency injection in TypeScript projects. This technology makes your code more modular, flexible, and testable by providing dependencies externally between classes. Dependency injection allows components to be tested independently while ensuring the application operates in a more organized and sustainable manner.</p><h3>TypeORM: For Database ORM Operations</h3><p>TypeORM is an ORM (Object-Relational Mapping) library developed for TypeScript and JavaScript. It allows interaction with the database without writing SQL queries. It manages relationships between the model and the database, simplifies data manipulation, and facilitates database migrations. Additionally, it offers database independence, enabling the seamless operation of the same application across different databases.</p><h3>AutoMapper: To Simplify Object Mapping Operations</h3><p>AutoMapper is a library that automates the transformation between objects. It is particularly useful for converting between data models and DTOs (Data Transfer Objects). This technology eliminates manual conversion processes, enabling faster and error-free data transfer. It provides a clean transition between APIs and database models, making the maintenance and expansion of the application easier.</p><h3>Repository Layer</h3><p>The repository layer provides a structure that directly interacts with the database and encapsulates all data operations. This layer is concerned solely with data reading, writing, and updating, and does not contain business logic. Database queries or ORM operations (such as TypeORM) are handled within this layer. The primary goal of the repository is to isolate other layers from database details, ensuring a cleaner and more organized structure.</p><p>In our project, there is a Repository Base that offers reusable infrastructure. This base provides a strong and flexible foundation for common use across the project.</p><pre>//For Example<br>@injectable()<br>export class TodoRepository extends RepositoryBase&lt;Todo&gt; {<br>  constructor(@inject(DependencyInjectionTokens.dataSource) Db: DataSource) {<br>    super(Todo, Db.manager);<br>  }<br>}</pre><h3>Business Layer</h3><p>The business layer is the structure that contains the application’s business logic and rules. This layer applies the necessary business rules to the data received from the repository layer and returns processed, refined data to upper layers.</p><p>In our project, there is a Business Base that enables the quick and organized development of business logic. This base provides a common infrastructure to facilitate the development of business rules.</p><pre>//For Example <br>@injectable()<br>export class TodoBusiness extends BusinessBase&lt;Todo&gt; {<br>  constructor(<br>    @inject(DependencyInjectionTokens.todoRepository)<br>    repository: TodoRepository,<br>  ) {<br>    super(repository);<br>  }</pre><pre>  getAll(): Promise&lt;Todo[]&gt; {<br>    return this.repository.getAll();<br>  }</pre><pre>  addAsync(params: Todo): Promise&lt;Todo&gt; {<br>    this.validationForAddAsync(params);</pre><pre>    return this.repository.insertAndGet(params);<br>  }</pre><pre>  async updateAsync(entity: Todo): Promise&lt;Todo&gt; {<br>    var existingTodo = await this.repository.getByClientId(entity.clientId);</pre><pre>    if (existingTodo == null) {<br>      throw ValidationException(&#39;Todo not found&#39;);<br>    }</pre><pre>    this.validationForUpdateAsync(entity);<br>    return this.repository.updateAndGet(entity);<br>  }</pre><pre>  deleteAsync(clientId: string): Promise&lt;void&gt; {<br>    this.validationForDelete(clientId);<br>    this.repository.softDelete(clientId);<br>    return Promise.resolve();<br>  }</pre><pre>  async validationForAddAsync(params: Todo): Promise&lt;boolean&gt; {<br>    if (ValidationUtils.isNullOrWhiteSpace(params.title)) {<br>      throw ValidationException(&#39;Title is required&#39;);<br>    }<br>    return true;<br>  }</pre><pre>  async validationForUpdateAsync(params: Todo): Promise&lt;boolean&gt; {<br>    ValidationUtils.idControl(params.clientId);</pre><pre>    return true;<br>  }</pre><pre>  async validationForDelete(clientId: string): Promise&lt;boolean&gt; {<br>    ValidationUtils.idControl(clientId);</pre><pre>    const todo = await this.repository.getByClientId(clientId!);</pre><pre>    if (!todo?.isCompleted &amp;&amp; todo?.todoDetails.length !== 0) {<br>      throw ValidationException(<br>        &#39;Todonun tüm detayları tamamlanmadan silinemez&#39;,<br>      );<br>    }</pre><pre>    return true;<br>  }<br>}</pre><h3>Service Layer</h3><p>The service layer acts as a bridge between the client and the business logic. This layer receives requests from the client, directs them to the business layer, and processes the results before returning them to the client in the appropriate format. Additionally, it performs data transformations, converting from DTO to entity or vice versa, and adjusts the data to suit the client’s needs.</p><p>The service layer also manages error handling and addresses errors when necessary. This structure abstracts the business logic from the user interface, ensuring that the application remains more organized and sustainable.</p><pre>//For Example<br>@injectable()<br>class TodoService {<br>  private todoBusiness: TodoBusiness;<br>  constructor(<br>    @inject(DependencyInjectionTokens.todoBusiness)<br>    todoBusiness: TodoBusiness<br>  ) {<br>    this.todoBusiness = todoBusiness;<br>  }</pre><pre>  async getTodos(): Promise&lt;TodoDto[]&gt; {<br>    const todoList = await this.todoBusiness.getAll();<br>    return mapper.mapArray(todoList, Todo, TodoDto);<br>  }</pre><pre>  @ServiceErrorHandler<br>  @UnitOfWork<br>  async createTodo(param: PostTodoParams): Promise&lt;TodoDto&gt; {<br>    const data = mapper.map(param, PostTodoParams, Todo);<br>    const todo = await this.todoBusiness.addAsync(data);</pre><pre>    return mapper.map(todo, Todo, TodoDto);<br>  }</pre><pre>  @ServiceErrorHandler<br>  @UnitOfWork<br>  async updateTodo(param: PutTodoParams): Promise&lt;TodoDto&gt; {<br>    const data = mapper.map(param, PutTodoParams, Todo);<br>    return mapper.map(await this.todoBusiness.updateAsync(data), Todo, TodoDto);<br>  }</pre><pre>  @ServiceErrorHandler<br>  @UnitOfWork<br>  async deleteTodo(id: string): Promise&lt;undefined&gt; {<br>    this.todoBusiness.deleteAsync(id);<br>    return undefined;<br>  }<br>}</pre><pre>export default container.resolve(TodoService);</pre><h3>Manage Data Transformations with Mapper</h3><p>In many applications, it is not appropriate to expose the data model (such as database models) directly to the UI or clients. Instead, it is necessary to transform data models into lighter and optimized structures called DTOs (Data Transfer Objects). To simplify this transformation, we use the @automapper library.</p><p>In this section, I will show you how to perform a mapping operation between Todo and TodoDto.</p><pre>import { createMapper, createMap, classes } from &#39;@automapper/classes&#39;;<br>import { Mapper } from &#39;@automapper/core&#39;;<br>import { Todo } from &#39;../entities/Todo&#39;;<br>import { TodoDto } from &#39;../dtos/TodoDto&#39;;</pre><pre>export const mapper: Mapper = createMapper({<br>  strategyInitializer: classes(),<br>});</pre><pre>// Mapping tanımı<br>createMap(mapper, Todo, TodoDto);</pre><h3>Unit of Work: Transaction Yönetimi ile Tutarlı ve Güvenilir Veri İşlemleri</h3><p>By integrating the @UnitOfWork decorator in the project, you can automate transaction management. This decorator ensures that all database operations performed within a transaction are executed under a single transaction scope. If an error occurs during the transaction, all changes are rolled back; if the transaction is successful, the changes are committed and made permanent.</p><p>The decorator dynamically resolves repositories, associates them with the transaction manager, and resets the manager at the end of the transaction to ensure data integrity. This allows developers to create a reliable and consistent transaction flow without manually managing transaction details.</p><pre>function UnitOfWork(_: any, __: string, descriptor: PropertyDescriptor) {<br>  const originalMethod = descriptor.value;</pre><pre>  descriptor.value = async function (...args: any[]) {<br>    const dataSource: DataSource = container.resolve(<br>      DependencyInjectionTokens.dataSource,<br>    );</pre><pre>    return await dataSource.transaction(<br>      async (transactionManager: EntityManager) =&gt; {<br>        const repositories = Object.keys(DependencyInjectionTokens)<br>          .filter(key =&gt; key.endsWith(&#39;Repository&#39;))<br>          .map(<br>            tokenKey =&gt;<br>              container.resolve(<br>                DependencyInjectionTokens[<br>                  tokenKey as keyof typeof DependencyInjectionTokens<br>                ],<br>              ) as RepositoryBase&lt;never&gt;,<br>          );</pre><pre>        repositories.forEach(repository =&gt; {<br>          repository.setManager(transactionManager);<br>        });</pre><pre>        try {<br>          transactionManager.queryRunner?.startTransaction();</pre><pre>          const result = await originalMethod.apply(this, args);</pre><pre>          await transactionManager.queryRunner?.commitTransaction();</pre><pre>          return result;<br>        } catch (error) {<br>          await transactionManager.queryRunner?.rollbackTransaction();<br>          throw error;<br>        } finally {<br>          repositories.forEach(repository =&gt; {<br>            repository.resetManager();<br>          });<br>          await transactionManager.queryRunner?.release();<br>        }<br>      },<br>    );<br>  };</pre><pre>  return descriptor;<br>}</pre><h3>Conclusion</h3><p>In this article, I have explained the layered architecture design used in my React Native TypeScript project and how it was implemented in practice using SQLite and TypeORM. This approach is particularly advantageous in terms of modularity, reusability, and extensibility.<br>You can find the full project with all details in the /src/offline services folder of the project via the link below.</p><p><a href="https://github.com/mhmtyasr/FullOfflineReactNativeApp">https://github.com/mhmtyasr/FullOfflineReactNativeApp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3ec5dd7cc6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full Offline Yaklaşımlı React Native Uygulama: Online-Offline Senkronizasyonun Gücü]]></title>
            <link>https://medium.com/@mhmtyasr/full-offline-yakla%C5%9F%C4%B1ml%C4%B1-react-native-uygulama-online-offline-senkronizasyonun-g%C3%BCc%C3%BC-90be717efd8d?source=rss-be5fa846cd67------2</link>
            <guid isPermaLink="false">https://medium.com/p/90be717efd8d</guid>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[offline-first]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Yasir Aktunç]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 18:59:38 GMT</pubDate>
            <atom:updated>2025-01-08T18:59:38.624Z</atom:updated>
            <content:encoded><![CDATA[<p>Ön bilgi: Bu Proje Offline first yaklaşımlı projelerden daha farklıdır.Bundan Dolayı full offline yaklaşımlı olarak tanımlanmıştır.</p><p>Mobil uygulama geliştirme süreçlerinde full offline yaklaşımlar, kullanıcıların internet bağlantısı olmadığında bile uygulamayı sorunsuz bir şekilde kullanmasını sağlar. Özellikle, <strong>Full Offline</strong> bir mimari, hem kullanıcı deneyimini artırır hem de uygulamanın güvenilirliğini artırır.</p><p>Bu yazıda, <strong>React Native</strong> kullanılarak geliştirilen ve çevrimdışı işlemleri destekleyen bir uygulamanın nasıl online hale geçtiğinde senkronize edileceğini detaylandırıyoruz. <strong>Offline işlemlerin online duruma geçtikten sonra backend’e aktarılması, iş mantığına göre işlenmesi ve mobil uygulamaya senkronize edilmesi</strong> sürecine odaklanıyoruz.</p><h3>Nerelerde Kullanabiliriz</h3><p>Özellikle full offline yaklaşımın tercih edildiği senaryolar şunlardır: Saha çalışmaları, zayıf internet bağlantısına sahip bölgeler veya uzun internet kesintilerinin olacağı ve kullanıcıların bloklanmaması gereken sistemlerde kullanılabilir.</p><h3>Nasıl Çalışır</h3><p>Bu sistem, mobil cihazların kesintisiz bir şekilde çevrimdışı ve çevrimiçi işlevsellik sunmasını sağlamak amacıyla tasarlanmıştır. Cihazlar uzun süre internete bağlı olmadan çalışabilir, internet bağlantısı geri geldiğinde ise veriler senkronize edilir. İşte sistemin nasıl çalıştığı:</p><ol><li><strong>Çevrimdışı Veri İşleme</strong><br>Cihaz çevrimdışı olduğunda, kullanıcılar uygulama ile etkileşimde bulunmaya devam edebilir ve yaptıkları işlemler yerel olarak SQLite veritabanına kaydedilir. Yeni eklenen veriler veya yapılan değişiklikler, bağlantı olmadığı sürece yerel veritabanında saklanır ve bu süreçte veri kaybı yaşanmaz. <strong>TypeORM</strong> kütüphanesi, veritabanı işlemlerini yöneterek çevrimdışı çalışmanın sorunsuz bir şekilde gerçekleşmesini sağlar.</li><li><strong>İş Mantığı Katmanı</strong><br><strong>Business katmanı</strong>, çevrimdışı ve çevrimiçi işlemlerin iş kurallarına uygun şekilde gerçekleşmesini sağlar. Çevrimdışı işlemler sırasında, sistem verileri yerel olarak depolar ve işleyerek senkronizasyon öncesi işlemleri tamamlar. Cihaz çevrimiçi olduğunda ise lojikler verilerin doğru şekilde backend’e aktarılmasını ve veri bütünlüğünü sağlar.</li><li><strong>Senkronizasyon Süreci</strong><br>Cihaz internet bağlantısı tespit ettiğinde, sistem senkronizasyon aşamasına geçer. Uygulama, son Senkronizasyon tarihinden sonra eklenen,güncellenen yada silinen tüm yerel verileri alır ve bunları backend sunucusuna yüklemeye çalışır. Bu yöntemle yalnızca değişiklikler veya yeni kayıtlar sunucuya gönderilir, bu da veri aktarımını minimize eder ve senkronizasyon süresini kısaltır. <strong>AutoMapper</strong> kütüphanesi, veri transfer objeleri (DTO) ile iş modelinin eşleşmesini sağlayarak veri tutarlılığını ve işlem kolaylığını artırır.</li><li><strong>Hata Yönetimi ve Bildirimler</strong><br>Çevrimdışı ve çevrimiçi süreçlerde sistem, kullanıcıyı bilgilendirir. Senkronizasyon sırasında bir hata meydana gelirse, örneğin bir çakışma veya yükleme hatası oluşursa, kullanıcıya bildirim gönderilir ve sistem hatayı çözmek için çözüm önerir ya da işlemi yeniden dener. Ayrıca, senkronizasyonun durumu hakkında kullanıcıya geri bildirim sağlanarak işlemlerin şeffaf bir şekilde gerçekleşmesi sağlanır.</li></ol><h3>Projede Bu İhtiyaç Nasıl Ortaya Çıktı?</h3><p>Bu projenin temelinde yatan ihtiyaç, <strong>kesintisiz kullanıcı deneyimi sağlama gerekliliği</strong> ve <strong>iş sürekliliğini koruma</strong> hedefiydi. İşte bu ihtiyacı ortaya çıkaran bazı temel sorunlar:</p><ol><li><strong>Zayıf İnternet Altyapısı:</strong><br>Uygulamanın kullanılacağı bölgelerdeki internet bağlantısı güvenilir değildi. Bu nedenle kullanıcıların, internet erişimi olmadığında bile verilerini kaydetmesi ve işlemlerini gerçekleştirebilmesi gerekiyordu.</li><li><strong>Çoklu Cihaz Senaryoları:</strong><br>Kullanıcıların farklı cihazlardan aynı verilere erişebilmesi gerekiyordu. Ancak, internet bağlantısı olmadan yapılan işlemlerin diğer cihazlarda senkronize edilebilmesi için bir çözüm gerekiyordu.</li></ol><h3>Projede bulunan Offline yaklaşımın diğer Offline yaklaşımlardan farkı nelerdir?</h3><h4><strong>Mobile uygulama içerisinde backendin bir yansımasının olması gerekliliği</strong>.</h4><p>Mobil uygulamalarda backend’in bir yansımasının bulunması, veri bütünlüğünü ve tutarlılığını sağlamak için kritik bir gerekliliktir. Tüm işlemlerde, backend tarafında uygulanan iş mantıklarının ve doğrulama süreçlerinin çevrimdışı modda mobil uygulamada da yer alması, hem kullanıcı deneyimini iyileştirir hem de senkronizasyon sırasında oluşabilecek veri tutarsızlıklarının önüne geçer.</p><h4>Backende erişelemiyor olması durumunda da mobile cihazın kullanabilir olması</h4><p>Mobil uygulamalar genellikle backendin ayakta olduğu durumda çalışır şekilde tasarlanmaktadır.Bizim mimarisimizde backende erişememe durumunda uygulamayı offline modda çalıştırıp hiç bir data kaybı olmadan tekrar erişebilir duruma tekrar geçtiğinde dataları senkronize edebiliriz.</p><h3>Projenin Genel Mimari Yapısı</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*mI3i2OyOB0c2hh27cic_pA.png" /></figure><p>Projemiz, <strong>Async Storage</strong> üzerinde tutulan lastSyncTime verisi temel alınarak çalışmaktadır. Bu veri, gönderilecek ya da alınacak verilerin son senkronizasyon tarihine göre hesaplanmasını sağlar.</p><p>Sistem, şu şekilde işlemektedir:</p><ul><li>lastSyncTime bilgisi kullanılarak, senkronizasyon yapılması gereken veriler belirlenir.</li><li>Belirlenen veriler, ihtiyaç durumuna göre backend’den alınır veya backend’e gönderilir.</li></ul><p>Bu yapı, veri transferlerinin optimize edilmesini ve senkronizasyon süreçlerinin daha verimli bir şekilde yönetilmesini sağlar.</p><h3>React Query ile Hookslar Üzerine Kurulu Proje Yapısı</h3><p>Projemiz, <strong>React Query</strong>’nin temel fonksiyonlarını soyutlayarak oluşturduğumuz özel fonksiyonlara dayanan bir yapı üzerine inşa edilmiştir. Bu yaklaşım sayesinde, kullanıcı arayüzü (UI) tarafı, projenin çevrimdışı mı yoksa çevrimiçi mi olduğundan bağımsız bir şekilde çalışabilir.</p><p>Bu yapı, uygulamanın esnekliğini artırırken, kullanıcı deneyimini çevrimdışı durumlarda bile kesintisiz hale getirir.</p><p>Aşağıda görebileceğiniz useBaseMutation ve useBaseQuery bu esnek yapıyı sağlamaktadır.</p><pre><br>const useBaseMutation = &lt;T, K extends BaseResponseDTO | undefined&gt;({<br>  service,<br>  offlineService,<br>  onSuccess,<br>  onError,<br>}: UseBaseMutationParams&lt;T, K | undefined&gt;) =&gt; {<br>  const {isConnected} = useInitializer();<br>  const toast = useToast();<br><br>  const {mutate, data, isError, isSuccess, isPending, error} = useMutation&lt;<br>    K | undefined,<br>    IBaseMutationError,<br>    T<br>  &gt;({<br>    onSuccess(_data) {<br>      handleSuccess(_data ?? undefined);<br>    },<br>    onError(_error, _data) {<br>      handleError(_error, _data);<br>    },<br>    mutationFn: e =&gt; {<br>      if (isConnected) {<br>        return service(e);<br>      } else {<br>        return offlineService!(e);<br>      }<br>    },<br>  });<br><br>  const handleSuccess: SuccessCallback&lt;K&gt; = async _data =&gt; {<br>    if (onSuccess?.callback) {<br>      onSuccess?.callback(_data);<br>    }<br>  };<br><br>  const handleError = async (_error: any, _data: T) =&gt; {<br>    if (onError?.callback) {<br>      onError.callback(_error);<br>    }<br>  };<br><br>  return {mutate, data, isError, isSuccess, isPending, error};<br>};<br><br>export default useBaseMutation;</pre><pre><br>import {useQuery} from &#39;@tanstack/react-query&#39;;<br>import {UseBaseQueryParams} from &#39;./types&#39;;<br>import {BaseRequestParams} from &#39;@/model/services/_base&#39;;<br>import {useCallback} from &#39;react&#39;;<br>import {useInitializer} from &#39;@/components/Initializer&#39;;<br>import {useToast} from &#39;@/components/Toast&#39;;<br><br>const useBaseQuery = &lt;<br>  ReqT extends BaseRequestParams | undefined,<br>  ResK,<br>  MappingT = ResK,<br>&gt;({<br>  service,<br>  offlineService,<br>  queryKeys,<br>  select,<br>  onSuccess,<br>  onError,<br>  enabled,<br>  initialData = undefined,<br>}: UseBaseQueryParams&lt;ReqT, ResK, MappingT&gt;) =&gt; {<br>  const {isConnected} = useInitializer();<br>  const queryFn = useCallback(<br>    async (e: any) =&gt; {<br>      if (isConnected) {<br>        return service(e.queryKey[1]);<br>      } else {<br>        if (offlineService) {<br>          return offlineService(e.queryKey[1]);<br>        }<br>        throw new Error(&#39;Offline service is not defined.&#39; + queryKeys);<br>      }<br>    },<br>    // eslint-disable-next-line react-hooks/exhaustive-deps<br>    [isConnected, queryKeys],<br>  );<br><br>  const {data, isError, isSuccess, isLoading, isFetching, error, refetch} =<br>    useQuery({<br>      queryKey: queryKeys,<br>      queryFn: queryFn,<br>      select: _data =&gt; {<br>        return select ? (select(_data as ResK) as any) : (_data as ResK);<br>      },<br>      retry: false,<br>      refetchOnMount: false,<br>      refetchOnReconnect: false,<br>      refetchOnWindowFocus: false,<br>      enabled: enabled,<br>      initialData: initialData,<br>    });<br><br>  if (isError) {<br>    if (onError?.callback) {<br>      onError.callback(error);<br>    }<br>  }<br><br>  if (isSuccess) {<br>    <br>    if (onSuccess?.callback) {<br>      onSuccess.callback(data);<br>    }<br>  }<br><br>  return {data, isError, isSuccess, isLoading, error, isFetching, refetch};<br>};<br><br>export default useBaseQuery;</pre><h3>Backend Çalışma Mekanizması</h3><p>Backend Post,Put ve Delete isteklerinden sonra sockete status code 200 olan default bir mesaj gönderir. Socketi dinleyen cihazlarda kendi son Senkronizasyon tarihine göre http isteği atarak değişen dataları backendden ister.</p><p>React Native Uygulamasının Backend Yapısı için İkinci Makale: SQLite ile Çok Katmanlı Backend Mimarisi</p><p><a href="https://medium.com/@mehmetyasiraktunc/react-nativede-sqlite-ile-%C3%A7ok-katmanl%C4%B1-backend-mimarisi-nas%C4%B1l-olu%C5%9Fturulur-44ef9427754c">https://medium.com/@mehmetyasiraktunc/react-nativede-sqlite-ile-%C3%A7ok-katmanl%C4%B1-backend-mimarisi-nas%C4%B1l-olu%C5%9Fturulur-44ef9427754c</a></p><p>Projenin tamamlanmış haline aşağıdaki GitHub deposundan ulaşabilirsiniz:<br><a href="https://github.com/mhmtyasr/FullOfflineReactNativeApp">https://github.com/mhmtyasr/FullOfflineReactNativeApp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90be717efd8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native’de SQLite ile Çok Katmanlı Backend Mimarisi Nasıl Oluşturulur?]]></title>
            <link>https://medium.com/@mhmtyasr/react-nativede-sqlite-ile-%C3%A7ok-katmanl%C4%B1-backend-mimarisi-nas%C4%B1l-olu%C5%9Fturulur-44ef9427754c?source=rss-be5fa846cd67------2</link>
            <guid isPermaLink="false">https://medium.com/p/44ef9427754c</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[automapper]]></category>
            <category><![CDATA[tsyringe]]></category>
            <category><![CDATA[sqlite3]]></category>
            <dc:creator><![CDATA[Yasir Aktunç]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 18:43:08 GMT</pubDate>
            <atom:updated>2024-12-16T18:43:50.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Native’de SQLite ile Çok Katmanlı Backend Mimarisi Nasıl Oluşturulur? (Windows,Ios ve Android destekli)</h3><p>Merhabalar, ben Yasir Aktunç. Web ve React Native geliştiricisiyim. Bugün sizlere, React Native TypeScript projemde kullandığım SQLite tabanlı backend mimarisini anlatacağım. Bu yapının en önemli özelliği, React Native Windows, Android ve iOS platformlarında mükemmel bir şekilde çalışıyor olmasıdır.</p><h3>Neden böyle bir mimariye ihtiyaç duyuyoruz</h3><p>Mobil uygulamalarda kullanılan backend mimarisi genellikle karmaşıktır ve platformlar arasında uyumluluk sorunları yaşanabilir. Amacım, SQLite gibi hafif bir veritabanını kullanarak hem performanslı, hem modüler, hem de test edilebilir bir backend yapısı oluşturmaktı. Aşağıda, backend yapımızın genel mimarisini görebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*mE5nvWKnG-NLvHMYFd-Nuw.png" /></figure><h3>Kullandığınız Teknolojiler</h3><h3>SQLite3: Veritabanı</h3><p><strong>SQLite3</strong>, React Native uygulamalarında veritabanı işlemlerini gerçekleştirmek için kullanılan hafif ve taşınabilir bir veritabanıdır. Genellikle depolama gereksinimleri için tercih edilir ve SQL sorguları kullanarak veri okuma, yazma, güncelleme ve silme işlemlerini kolaylaştırır. SQLite, sunucuya bağlı olmayan, tek dosya tabanlı bir veritabanıdır ve küçük ölçekli uygulamalarda performans ile kaynak kullanımı açısından oldukça etkili bir çözüm sunar.</p><h3><strong>Tsyringe</strong>: Bağımlılık Enjeksiyonu ile Modüler Bir Yapı İçin</h3><p><strong>Tsyringe</strong>, TypeScript projelerinde bağımlılık enjeksiyonu uygulamak için kullanılan bir kütüphanedir. Bu teknoloji, sınıflar arasındaki bağımlılıkları dışarıdan sağlayarak kodunuzu daha modüler, esnek ve test edilebilir hale getirir. Bağımlılık enjeksiyonu (Dependency Injection), bileşenlerin bağımsız olarak test edilmesine olanak tanırken, uygulamanın daha düzenli ve sürdürülebilir bir yapıda çalışmasını sağlar.</p><h3>Typeorm: Veritabanı ORM İşlemleri İçin</h3><p><strong>Typeorm</strong>, TypeScript ve JavaScript için geliştirilmiş bir ORM (Nesne-İlişkisel Haritalama) kütüphanesidir. SQL sorguları yazmadan veritabanı ile etkileşim kurmayı sağlar. Model ile veritabanı arasındaki ilişkileri yönetir, veri manipülasyonunu basitleştirir ve veritabanı migrasyonlarını kolaylaştırır. Ayrıca, veritabanı bağımsızlığı sunarak farklı veritabanlarında aynı uygulamanın sorunsuz bir şekilde çalışmasını destekler.</p><h3>Automapper: Nesne Dönüştürme İşlemlerini Kolaylaştırmak İçin</h3><p><strong>Automapper</strong>, nesneler arasındaki dönüşümleri otomatikleştiren bir kütüphanedir. Özellikle DTO’lar (Data Transfer Object) ile veri modelleri arasındaki dönüşümlerde sıklıkla kullanılır. Bu teknoloji, manuel dönüşüm işlemlerini ortadan kaldırarak veri aktarımını daha hızlı ve hatasız bir şekilde gerçekleştirir. API’ler ve veritabanı modelleri arasında temiz bir geçiş sağlar, böylece uygulamanın bakımını ve genişletilmesini kolaylaştırır.</p><h3>Repository Katmanı</h3><p>Repository katmanı, veritabanıyla doğrudan etkileşim kuran ve tüm veri işlemlerini kapsülleyen bir yapı sunar. Bu katman, yalnızca veri okuma, yazma ve güncelleme işlemleriyle ilgilenir; iş mantığını içermez. Veritabanı sorguları veya ORM (örneğin, TypeORM) işlemleri bu katmanda yer alır. Repository’nin temel amacı, diğer katmanları veritabanı ayrıntılarından izole ederek daha temiz ve düzenli bir yapı sağlamaktır.</p><p>Projemizde, tekrar kullanılabilir bir altyapı sunan bir <strong>Repository Base</strong> bulunuyor. Bu base, proje genelinde ortak kullanım için güçlü ve esnek bir temel sağlar.</p><pre>//Örnek bir Repository örnegi<br>@injectable()<br>export class TodoRepository extends RepositoryBase&lt;Todo&gt; {<br>  constructor(@inject(DependencyInjectionTokens.dataSource) Db: DataSource) {<br>    super(Todo, Db.manager);<br>  }<br>}</pre><h3>Business Katmanı</h3><p>Business katmanı, uygulamanın iş mantığını ve kurallarını barındıran yapıdır. Bu katman, Repository katmanından alınan veriler üzerinde gerekli iş kurallarını uygular ve üst katmanlara işlenmiş, temizlenmiş veriler döner.</p><p>Projemizde, iş mantıklarının hızlı ve düzenli bir şekilde yazılmasını sağlayan bir <strong>Business Base</strong> bulunmaktadır. Bu base, iş kurallarını daha kolay geliştirmek için ortak bir altyapı sunar.</p><pre>//Örnek bir Todo Business <br>@injectable()<br>export class TodoBusiness extends BusinessBase&lt;Todo&gt; {<br>  constructor(<br>    @inject(DependencyInjectionTokens.todoRepository)<br>    repository: TodoRepository,<br>  ) {<br>    super(repository);<br>  }<br><br>  getAll(): Promise&lt;Todo[]&gt; {<br>    return this.repository.getAll();<br>  }<br><br>  addAsync(params: Todo): Promise&lt;Todo&gt; {<br>    this.validationForAddAsync(params);<br><br>    return this.repository.insertAndGet(params);<br>  }<br><br>  async updateAsync(entity: Todo): Promise&lt;Todo&gt; {<br>    var existingTodo = await this.repository.getByClientId(entity.clientId);<br><br>    if (existingTodo == null) {<br>      throw ValidationException(&#39;Todo not found&#39;);<br>    }<br><br>    this.validationForUpdateAsync(entity);<br>    return this.repository.updateAndGet(entity);<br>  }<br><br>  deleteAsync(clientId: string): Promise&lt;void&gt; {<br>    this.validationForDelete(clientId);<br>    this.repository.softDelete(clientId);<br>    return Promise.resolve();<br>  }<br><br>  async validationForAddAsync(params: Todo): Promise&lt;boolean&gt; {<br>    if (ValidationUtils.isNullOrWhiteSpace(params.title)) {<br>      throw ValidationException(&#39;Title is required&#39;);<br>    }<br>    return true;<br>  }<br><br>  async validationForUpdateAsync(params: Todo): Promise&lt;boolean&gt; {<br>    ValidationUtils.idControl(params.clientId);<br><br>    return true;<br>  }<br><br>  async validationForDelete(clientId: string): Promise&lt;boolean&gt; {<br>    ValidationUtils.idControl(clientId);<br><br>    const todo = await this.repository.getByClientId(clientId!);<br><br>    if (!todo?.isCompleted &amp;&amp; todo?.todoDetails.length !== 0) {<br>      throw ValidationException(<br>        &#39;Todonun tüm detayları tamamlanmadan silinemez&#39;,<br>      );<br>    }<br><br>    return true;<br>  }<br>}</pre><h3>Servis Katmanı</h3><p>Servis katmanı, istemci ile iş mantığı arasında bir köprü görevi görür. Bu katman, istemciden gelen istekleri alır, Business katmanına yönlendirir ve oradan dönen sonuçları uygun şekilde işleyerek istemciye iletir. Ayrıca, veri dönüşümleri gerçekleştirerek DTO’dan entity’ye ya da entity’den DTO’ya dönüşüm yapar ve veriyi istemciye uygun hale getirir.</p><p>Servis katmanı, aynı zamanda hata davranışlarını yönetir ve gerekli durumlarda hataları ele alır. Bu yapı, iş mantığını kullanıcı arayüzünden tamamen soyutlayarak uygulamanın daha düzenli ve sürdürülebilir olmasını sağlar.</p><pre>//Örnek bir Servis katmanımız<br>@injectable()<br>class TodoService {<br>  private todoBusiness: TodoBusiness;<br>  constructor(<br>    @inject(DependencyInjectionTokens.todoBusiness)<br>    todoBusiness: TodoBusiness<br>  ) {<br>    this.todoBusiness = todoBusiness;<br>  }<br><br>  async getTodos(): Promise&lt;TodoDto[]&gt; {<br>    const todoList = await this.todoBusiness.getAll();<br>    return mapper.mapArray(todoList, Todo, TodoDto);<br>  }<br><br>  @ServiceErrorHandler<br>  @UnitOfWork<br>  async createTodo(param: PostTodoParams): Promise&lt;TodoDto&gt; {<br>    const data = mapper.map(param, PostTodoParams, Todo);<br>    const todo = await this.todoBusiness.addAsync(data);<br><br>    return mapper.map(todo, Todo, TodoDto);<br>  }<br><br>  @ServiceErrorHandler<br>  @UnitOfWork<br>  async updateTodo(param: PutTodoParams): Promise&lt;TodoDto&gt; {<br>    const data = mapper.map(param, PutTodoParams, Todo);<br>    return mapper.map(await this.todoBusiness.updateAsync(data), Todo, TodoDto);<br>  }<br><br>  @ServiceErrorHandler<br>  @UnitOfWork<br>  async deleteTodo(id: string): Promise&lt;undefined&gt; {<br>    this.todoBusiness.deleteAsync(id);<br>    return undefined;<br>  }<br>}<br><br>export default container.resolve(TodoService);</pre><h3>Mapper ile Veri Dönüşümlerini Yönetin</h3><p>Birçok uygulamada, veri modelini (örneğin, veritabanı modelleri) doğrudan UI’ya veya istemcilere sunmak doğru bir yaklaşım değildir. Bunun yerine, veri modellerini daha hafif ve optimize edilmiş yapılar olan DTO’lara (Data Transfer Object) dönüştürmek gereklidir. Bu dönüşümü kolaylaştırmak için <strong>@automapper</strong> kütüphanesini kullanıyoruz.</p><p>Bu bölümde, <strong>Todo</strong> ve <strong>TodoDto</strong> arasında bir eşleme (mapping) işlemini nasıl gerçekleştireceğinizi göstereceğim.</p><pre>import { createMapper, createMap, classes } from &#39;@automapper/classes&#39;;<br>import { Mapper } from &#39;@automapper/core&#39;;<br>import { Todo } from &#39;../entities/Todo&#39;;<br>import { TodoDto } from &#39;../dtos/TodoDto&#39;;<br><br>export const mapper: Mapper = createMapper({<br>  strategyInitializer: classes(),<br>});<br><br>// Mapping tanımı<br>createMap(mapper, Todo, TodoDto);<br></pre><h3>Unit of Work: Transaction Yönetimi ile Tutarlı ve Güvenilir Veri İşlemleri</h3><p>Projede bulunan <strong>@UnitOfWork</strong> dekoratörünü entegre ederek transaction yönetimini otomatikleştirebilirsiniz. Bu dekoratör sayesinde, işlem içinde gerçekleştirilen tüm veritabanı işlemleri tek bir transaction kapsamında yürütülür. Eğer işlem sırasında bir hata oluşursa, yapılan tüm değişiklikler geri alınır (rollback); işlem başarıyla tamamlanırsa, değişiklikler kalıcı hale getirilir (commit).</p><p>Dekoratör, repository’leri dinamik olarak çözer, transaction yöneticisiyle ilişkilendirir ve işlem sonunda yöneticiyi sıfırlayarak veri bütünlüğünü sağlar. Bu sayede geliştiriciler, transaction detaylarını manuel olarak yönetmek zorunda kalmadan güvenilir ve tutarlı bir işlem akışı oluşturabilir.</p><pre>function UnitOfWork(_: any, __: string, descriptor: PropertyDescriptor) {<br>  const originalMethod = descriptor.value;<br><br>  descriptor.value = async function (...args: any[]) {<br>    const dataSource: DataSource = container.resolve(<br>      DependencyInjectionTokens.dataSource,<br>    );<br><br>    return await dataSource.transaction(<br>      async (transactionManager: EntityManager) =&gt; {<br>        const repositories = Object.keys(DependencyInjectionTokens)<br>          .filter(key =&gt; key.endsWith(&#39;Repository&#39;))<br>          .map(<br>            tokenKey =&gt;<br>              container.resolve(<br>                DependencyInjectionTokens[<br>                  tokenKey as keyof typeof DependencyInjectionTokens<br>                ],<br>              ) as RepositoryBase&lt;never&gt;,<br>          );<br><br>        repositories.forEach(repository =&gt; {<br>          repository.setManager(transactionManager);<br>        });<br><br>        try {<br>          transactionManager.queryRunner?.startTransaction();<br><br>          const result = await originalMethod.apply(this, args);<br><br>          await transactionManager.queryRunner?.commitTransaction();<br><br>          return result;<br>        } catch (error) {<br>          await transactionManager.queryRunner?.rollbackTransaction();<br>          throw error;<br>        } finally {<br>          repositories.forEach(repository =&gt; {<br>            repository.resetManager();<br>          });<br>          await transactionManager.queryRunner?.release();<br>        }<br>      },<br>    );<br>  };<br><br>  return descriptor;<br>}</pre><h3>Sonuç</h3><p>Bu makalede, React Native TypeScript projemde kullanılan katmanlı mimari tasarımını ve SQLite ile TypeORM kullanarak bunun nasıl gerçek hayata geçirildiğini açıkladım. Özellikle modülerlik, tekrar kullanılabilirlik ve genişletilebilirlik açısından bu yaklaşım oldukça avantajlıdır.</p><p>Projeyi tüm detaylarıyla aşağıdaki bağlantıda bulunan projenin /src/<strong>offline services</strong> klasöründe bulabilirsiniz.</p><p><a href="https://github.com/mhmtyasr/FullOfflineReactNativeApp">https://github.com/mhmtyasr/FullOfflineReactNativeApp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44ef9427754c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MarkerFlow Chrome Extension]]></title>
            <link>https://medium.com/@mhmtyasr/markerflow-chrome-extension-901284a41ede?source=rss-be5fa846cd67------2</link>
            <guid isPermaLink="false">https://medium.com/p/901284a41ede</guid>
            <dc:creator><![CDATA[Yasir Aktunç]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 16:34:05 GMT</pubDate>
            <atom:updated>2024-03-27T19:53:52.431Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is the markerFlow</strong></p><p>Marker Flow is a simple Chrome application that allows you to create a new topic on a website, support it with a marker, or add a comment to an existing topic. The project includes a web site and an extension both written in React, as well as a GitHub repository containing an API developed using .NET Core. Backend operations are implemented using the ABP (Asp.Net Boilerplate) framework, supporting basic CRUD (Create, Read, Update, Delete) operations and enabling the system to be multitenant.</p><p>The project operates within an iframe between the web site and the extension, facilitating data exchange through the use of postMessage. Both sides trigger their own events and listen for incoming data from the other.</p><p>The web site communicates the positions of pins and cards to the extension, while the extension sends back the position of the created pin to the web site. The extension scans the DOM every second to find the positions of pins and uses multiple pieces of data to determine the pin’s location. An example pin data can be found below.</p><pre>{<br>  &quot;selector&quot;: &quot;body &gt; div:nth-child(9) &gt; div &gt; div &gt; div:nth-child(4) &gt; div &gt; div:nth-child(1) &gt; h1&quot;,<br>  &quot;coords&quot;: {<br>    &quot;x&quot;: 49,<br>    &quot;y&quot;: 70.69996643066406, <br>    &quot;width&quot;: 431,<br>    &quot;height&quot;: 150,<br>    &quot;xRate&quot;: 0.1136890951276102, <br>    &quot;yRate&quot;: 0.4713331095377604<br>  },<br>  &quot;id&quot;: &quot;&quot;,<br>  &quot;tagName&quot;: &quot;h1&quot;,<br>  &quot;textContent&quot;: &quot;CSS&quot;,<br>  &quot;outerHTML&quot;: &quot;&lt;h1 style=\&quot;font-size:100px;font-weight:700\&quot;&gt;CSS&lt;/h1&gt;&quot;<br>}</pre><h3>Artitecture</h3><p>This project involves three main components: the Chrome Extension, the Web Site, and the API.</p><p>Extension:: Extension: The extension operates by running the website within an iframe and communicates through post message to send and receive data.When get data from postMessage ,Push event and trigger component cycle</p><p>Web Site: :It is a web application running inside an iframe, capable of receiving and sending data through post message in communication with the extension.When get data from postMessage ,Push event and trigger component cycle</p><p>Api: Our backend services perform CRUD (Create, Read, Update, Delete) operations using Axios to facilitate data exchange between the extension and the web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*-0sxVnwBoRUXQ96GUqHKKg.png" /></figure><p>The website and extension trigger an event upon receiving data from the postMessage channel, allowing the necessary components to receive this data. For example, a component responsible for drawing pins on the screen listens for the pin data received from the postMessage channel and proceeds to draw the pins on the screen.</p><h3>Project Setup Instructions</h3><p>Follow these steps to set up the development environment for the “markerFlow Chrome Extension” project:</p><h3>Step 1: Run the Backend Host</h3><p>Navigate to the backend project directory and run the host.</p><h3>Step 2: Run the Website</h3><pre>cd website<br>yarn install<br>yarn run dev</pre><h3>Step 2: Load Extension in Chrome</h3><pre>Open Google Chrome.<br>Navigate to chrome://extensions/.<br>Enable &quot;Developer mode&quot; in the top right corner.<br>Click on &quot;Load unpacked&quot; and select the dist folder in your extension project.<br>The extension is now loaded in your Chrome browser.</pre><p>The source codes for the backend, web page, and a ready-made Chrome extension are available on the GitHub repository.</p><p><a href="https://github.com/mhmtyasr/markerFlowV2">https://github.com/mhmtyasr/markerFlowV2</a></p><p>Extension Video and ScreenShots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Sclcc5-oEaVEMYqZDQ7ZEA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-JEEVvSQsdK9mkJjUZDbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8Tdb8d0dlYM5aZJ_ysWjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*9AsIOVXClbtGRmOwiLzz9w.png" /></figure><p>If you have any questions, you can reach out to me on <a href="https://www.linkedin.com/in/mhmtyasr/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=901284a41ede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create UMD Package using webpack for ResiumJs (CesiumJS)]]></title>
            <link>https://medium.com/@mhmtyasr/resium-js-for-umd-package-with-webpack-e1c534f88fbd?source=rss-be5fa846cd67------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1c534f88fbd</guid>
            <category><![CDATA[umd]]></category>
            <category><![CDATA[cesiumjs]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Yasir Aktunç]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 11:48:11 GMT</pubDate>
            <atom:updated>2023-12-16T13:05:43.422Z</atom:updated>
            <content:encoded><![CDATA[<p>Uzun bir süre boyunca internet üzerinde araştırma yapmama rağmen istediğim paketi bulamadım ve sonunda kendi paketimi oluşturmak zorunda kaldım. Eğer Resium’u kullanacaksanız, ResiumJS CesiumJS içinde bulunan .cjs dosyası ile uyumludur, ancak bu dosyayı bulamadığımız için UMD paketi oluşturamıyoruz. ResiumJS&#39;in kaynak kodunu indirip src klasörü içindeki bileşenlerde bulunan aşağıdaki kodu silip, yerine @cesium/engine ve @cesium/widgets ekleyebilirsiniz.</p><pre>//---- import {Entity,View} from &quot;cesium&quot; ;<br>//+++++ import {Entity} from &quot;@cesium/engine&quot;;<br>//+++++ import {View} from &quot;@cesium/widgets&quot;;</pre><p>Son olarak, window.CESIUM_BASE_URL&#39;yi https://cdnjs.cloudflare.com/ajax/libs/cesium/1.107.2 şeklinde ayarladığınızda, CesiumJS ile doğrudan bir bağlantımız kalmamaktadır. Ancak bu şekilde CDN üzerinden assetlere erişebiliyoruz. Ayrıca, @cesium/engine ve @cesium/widgets kullanarak ResiumJS üzerinden istediğimiz işlemleri gerçekleştirebiliyoruz. İlgili kod örneklerini aşağıdaki depoda bulabilirsiniz:</p><p><a href="https://github.com/mhmtyasr/resiumjs/">https://github.com/mhmtyasr/resiumjs/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1c534f88fbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Plugin System and Dynamic Layout in React]]></title>
            <link>https://medium.com/@mhmtyasr/dynamic-plugin-system-and-dynamic-layout-in-react-fe88f8d8e135?source=rss-be5fa846cd67------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe88f8d8e135</guid>
            <dc:creator><![CDATA[Yasir Aktunç]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 19:33:38 GMT</pubDate>
            <atom:updated>2023-09-01T07:39:10.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello dear readers! In this article, we will explore how we can create a dynamic plugin system using React and how to run these plugins in a flexible layout. We will also learn how to integrate custom UMD React plugins from GitHub, how to access the Context API and how to communicate between plugins.</p><h3>Project Story</h3><p>Our project was born out of a need to enable users to create and run their own plugins, but this was different from the micro-frontend approach of running multiple projects on different ports and consolidating them into one central point. What was wanted was for users to be able to install their plugins instantly and for other users to be able to see them immediately in the same layout. And this without any deployment or updates. This need allowed us to break away from the traditional micro-frontend approach. In the system we created, everything happens instantly and works within a single React project without the need to restart the entire pr</p><h3>Creating Plugin Components</h3><p>Our plugins are delivered as a special UMD (Universal Module Definition) package. This package requires a specific libraryName to run. We need this libraryName to run the plugin. To minimize the size of plugins, our main project passes packages like React, React-dom and Antd to other plugins via the window object. In this way, these packages are used as externals within the plugins and reduce the plugin size significantly.</p><pre>// When plugins are created, a default plugin is created, as in the following example. <br>// The &quot;getAttributes&quot; function must be added.<br>// Otherwise, the component cannot be rendered.</pre><pre>export const getAttributes = () =&gt; {<br>  return {<br>    name: packageJson.name, // Arayüz amaçlı kullanılır<br>    libraryName: packageJson.libraryName, //Unique<br>    version: packageJson.version, // Version<br>    service: { <br>      name: packageJson.libraryName, // The other plugins of this                      <br>                                     // plugin to access the context<br>      provider: TestProvider,<br>      contextApi: TestContext,<br>      defaultValue: {},<br>    },<br>  };<br>};</pre><pre>// The following data is props by default when plugins are run <br>// is passed as:<br>// - UseAuth: the default Auth context api of the project<br>// - GetContextApi(&quot;libraryName&quot;): To access other context apis // //function used</pre><pre>const Plugin = ({ useAuth, getContextApi }) =&gt; {<br>  const { missionData, handleAddMissionData } = React.useContext(<br>    getContextApi(&quot;testPluginWithProvider&quot;) // Benzersiz Library Name<br>  );</pre><pre>  const { userName, setUserName } = useAuth(); // Default Context Api</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;Welcome, {userName}!&lt;/h2&gt;<br>        &lt;button onClick={() =&gt; handleAddMissionData(&quot;New Mission&quot;)}&gt;<br>          Yeni Görev Ekle<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><pre>//Example Basic Plugin component</pre><p>In the GitHub repository below, you can find examples that explain this approach and include three different plugin scenarios. These examples will walk you through how to write a plugin.</p><p><a href="https://github.com/mhmtyasr/react-plugin-packages">GitHub - mhmtyasr/react-plugin-packages</a></p><p>Sistemde Kullanılan Ana Kütüphaneler</p><p>The basic libraries used in our project are as follows:</p><ul><li><strong>Dynamic Layout: flexlayout-react</strong>: It is a library we use to create and manage the flexible layout of our application. With this library we can dynamically position components and manage the layout.</li><li><strong>For Fetch: Axios: </strong>It is our preferred library for managing network requests between the application and the server. Thanks to the ease of use that Axios provides, we can perform data exchange operations effectively.</li><li><strong>UI Library: Ant Design (Antd):</strong> We prefer the Antd library for user interface components. With ready-made components, we can achieve a fast and elegant look and improve the user experience.</li></ul><p>At this stage, we completed the plugins we developed and successfully obtained the relevant <strong>UMD (Universal Module Definition)</strong> outputs.</p><p>Running the Project and Viewing Plugins</p><p>The project we have developed can be operated in the following steps:</p><ol><li>Github Repository Clone</li></ol><pre>git clone https://github.com/mhmtyasr/react-dynamic-plugin-system</pre><ol><li>Install the required dependencies and start the project:</li></ol><pre>yarn install &amp;&amp; yarn start</pre><ul><li>The project has two main pages:: <strong>“Design Layout” </strong>and <strong>“Show Layout”</strong>.</li><li><strong>Design Layout</strong>: This page has an interface where we can drag and drop plugins to the desired positions in the layout. We can then save the edits made. The layout data is stored in local storage.</li><li><strong>Show Layout:</strong> This page creates a dynamic layout using layout data stored in local storage. When the page is loaded, the “Dynamic Provider” context api runs first. This component creates a “context API” that all other plugins can access. The context APIs of the plugins, if any, are added to this general structure. Then, the components on the window object are rendered to the screen with the help of the following component.</li></ul><pre>const PluginViewer: React.FC&lt;IPluginUIModel&gt; = (plugin: IPluginUIModel) =&gt; {<br>  const [Component, setComponent] = useState&lt;any&gt;(null);<br>  const { getContextApi } = useDynamic();</pre><pre>  useEffect(() =&gt; {<br>   <br>    var creator = window[plugin.libraryName!] as any;<br>    <br>    if (creator &amp;&amp; creator.default) {<br>      setComponent(creator);<br>    }<br>  }, []);</pre><pre>  const Plugin = React.lazy(() =&gt; {<br>    return Component ? Promise.resolve(Component) : Promise.resolve(() =&gt; {});<br>  });</pre><pre>  return (<br>    &lt;React.Suspense fallback={&lt;Spin tip=&quot;Plugin Uploading...&quot; /&gt;}&gt;<br>      {Component ? (<br>        &lt;Plugin useAuth={useAuth} getContextApi={getContextApi} /&gt;<br>      ) : (<br>        &lt;Spin tip=&quot;Plugin Uploading...&quot; /&gt;<br>      )}<br>    &lt;/React.Suspense&gt;<br>  );<br>};</pre><pre>export default React.memo(PluginViewer, (prev, next) =&gt; {<br>  return prev.libraryName === next.libraryName;<br>});</pre><p>For code samples and more details, you can check out the GitHub repository for the project:</p><p><a href="https://github.com/mhmtyasr/react-dynamic-plugin-system">GitHub - mhmtyasr/react-dynamic-plugin-system</a></p><h3>LİVE VERSİON</h3><p><a href="https://react-dynamic-plugin-system.vercel.app/">React App</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe88f8d8e135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React’te Dinamik Plugin Sistemi ve Dinamik Layout]]></title>
            <link>https://medium.com/@mhmtyasr/reactte-dinamik-plugin-sistemi-ve-dinamik-layout-156a8c041ca8?source=rss-be5fa846cd67------2</link>
            <guid isPermaLink="false">https://medium.com/p/156a8c041ca8</guid>
            <dc:creator><![CDATA[Yasir Aktunç]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 20:55:34 GMT</pubDate>
            <atom:updated>2025-08-20T21:46:43.377Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba sevgili okuyucular! Bu makalede, React kullanarak nasıl dinamik bir eklenti sistemi oluşturabileceğimizi ve bu eklentilerin esnek bir düzende nasıl çalıştırılacağını keşfedeceğiz. Aynı zamanda, GitHub’dan alınan özel UMD React eklentilerinin nasıl entegre edileceğini, Context API sistemine nasıl erişileceğini ve eklentiler arasında nasıl iletişim kurulabileceğini öğreneceğiz.</p><h3>Projenin Arka Planı</h3><p>Projemiz, kullanıcıların kendi eklentilerini oluşturup çalıştırabilmelerini sağlayan bir gereksinimle doğdu. Ancak bu gereksinim, mikro ön yüz yapısındaki gibi farklı portlarda birden fazla projeyi çalıştırma ve bu projeleri tek bir merkezi noktada birleştirme yaklaşımından farklıydı. İstenen, kullanıcıların eklentilerini anında yükleyebilmeleri ve diğer kullanıcıların da aynı düzende bu eklentileri hemen görebilmeleriydi. Üstelik herhangi bir dağıtım veya güncelleme gerektirmeden bunu yapabilmesiydi. Bu ihtiyaç, geleneksel mikro ön yüz yaklaşımından ayrılmamızı sağladı. Oluşturduğumuz sistemde her şey anlık olarak gerçekleşiyor ve tüm projeyi yeniden başlatmaya gerek kalmadan tek bir React projesi içerisinde çalışıyor.</p><h3>Eklenti Bileşenlerini Oluşturma</h3><p>Eklentilerimiz özel bir UMD (Universal Module Definition) paketi olarak sunuluyor. Bu paket, çalıştırabilmek için belirli bir libraryName gerektirir. Eklentiyi çalıştırmak için bu libraryName değerine ihtiyacımız vardır. Eklentilerin boyutunu etmek için ana projemiz, React, React-dom ve Antd gibi paketleri diğer eklentilere window nesnesi üzerinden iletiyor. Bu sayede, gönderilen bu paketler, eklentiler içinde externals olarak kullanılıyor ve eklenti boyutunu ciddi şekilde küçültüyor.</p><pre>// Plugin&#39;ler oluşturulurken, aşağıdaki örnekte olduğu gibi varsayılan bir <br>// &quot;getAttributes&quot; fonksiyonu eklenmesi gerekmektedir.<br>// Aksi takdirde, bileşen render edilemez.<br><br>export const getAttributes = () =&gt; {<br>  return {<br>    name: packageJson.name, // Arayüz amaçlı kullanılır<br>    libraryName: packageJson.libraryName, // Benzersiz bir tanımlayıcı<br>    version: packageJson.version, // Sürüm bilgisi<br>    service: { <br>      name: packageJson.libraryName, // Diğer pluginlerin bu pluginin <br>                                     //contextine erişmesi için<br>      provider: TestProvider,<br>      contextApi: TestContext,<br>      defaultValue: {},<br>    },<br>  };<br>};<br><br>// Plugin&#39;ler çalıştırıldığında aşağıdaki veriler varsayılan olarak props <br>// olarak iletilir:<br>// - UseAuth: Projenin varsayılan Auth context api&#39;si<br>// - GetContextApi(&quot;libraryName&quot;): Diğer context apilerine erişmek için <br>// kullanılan fonksiyon<br><br>const Plugin = ({ useAuth, getContextApi }) =&gt; {<br>  const { missionData, handleAddMissionData } = React.useContext(<br>    getContextApi(&quot;testPluginWithProvider&quot;) // Benzersiz Library Name<br>  );<br><br>  const { userName, setUserName } = useAuth(); // Default Context Api<br><br>  return (<br>    &lt;&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;Hoşgeldin, {userName}!&lt;/h2&gt;<br>        &lt;button onClick={() =&gt; handleAddMissionData(&quot;Yeni Görev&quot;)}&gt;<br>          Yeni Görev Ekle<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>//Example Basic Plugin component</pre><p>Aşağıdaki GitHub deposunda, bu yaklaşımı açıklayan ve üç farklı eklenti senaryosunu içeren örnekler bulabilirsiniz. Bu örnekler, bir plugini nasıl yazabilirsiniz sorusunda size yol gösterecektir.</p><p><a href="https://github.com/mhmtyasr/react-plugin-packages">GitHub - mhmtyasr/react-plugin-packages</a></p><p>Sistemde Kullanılan Ana Kütüphaneler</p><p>Projemizde kullanılan temel kütüphaneler aşağıdaki gibidir:</p><ul><li><strong>Dinamik Layout Sistemi İçin: flexlayout-react</strong>: Uygulamamızın esnek düzenini oluşturmak ve yönetmek için kullandığımız bir kütüphanedir. Bu kütüphane sayesinde bileşenleri dinamik olarak konumlandırabilir ve düzeni yönetebiliriz.</li><li><strong>Network İşlemleri İçin: Axios: </strong>Uygulama ile sunucu arasındaki ağ isteklerini yönetmek için tercih ettiğimiz bir kütüphanedir. Axios’un sağladığı kolay kullanım sayesinde veri alışverişi işlemlerini etkili bir şekilde gerçekleştirebiliriz.</li><li><strong>UI Kütüphanesi: Ant Design (Antd):</strong> Kullanıcı arayüzü bileşenleri için Antd kütüphanesini tercih ediyoruz. Hazır bileşenler sayesinde hızlı ve şık bir görünüm elde edebilir, kullanıcı deneyimini geliştirebiliriz.</li></ul><p>Bu aşamada geliştirdiğimiz eklentileri tamamladık ve ilgili <strong>UMD (Universal Module Definition)</strong> çıktılarını başarılı bir şekilde elde ettik.</p><p>Projeyi Çalıştırma ve Eklentileri Görüntüleme</p><p>Geliştirdiğimiz proje şu adımlarla çalıştırılabilir:</p><ol><li>İlgili GitHub reposunu klonlayın:</li></ol><pre>git clone https://github.com/mhmtyasr/react-dynamic-plugin-system</pre><ol><li>Gerekli bağımlılıkları yükleyin ve projeyi başlatın:</li></ol><pre>yarn install &amp;&amp; yarn start</pre><ol><li>Projede iki ana sayfa bulunmaktadır: <strong>“Design Layout” </strong>ve <strong>“Show Layout”</strong>.</li></ol><ul><li><strong>Design Layout</strong>: Bu sayfa, sürükle-bırak yöntemiyle eklentileri layoutta istediğimiz konumlara yerleştirebildiğimiz bir arayüze sahiptir. Ardından yapılan düzenlemeleri kaydedebiliriz. Düzen verileri yerel depolama (local storage) alanında saklanır.</li><li><strong>Show Layout:</strong> Bu sayfa, yerel depolamada saklanan düzen verilerini kullanarak dinamik bir düzen oluşturur. Sayfa yüklendiğinde, önce “Dynamic Provider” context api çalışır. Bu bileşen, diğer tüm eklentilerin erişebileceği bir “context API” oluşturur. Eğer varsa, eklentilerin içerdikleri context API’leri bu genel yapıya eklenir. Daha sonra, pencere nesnesi üzerinde bulunan bileşenler, aşağıda belirtilen bileşen yardımıyla ekrana render edilir.</li></ul><pre>const PluginViewer: React.FC&lt;IPluginUIModel&gt; = (plugin: IPluginUIModel) =&gt; {<br>  const [Component, setComponent] = useState&lt;any&gt;(null);<br>  const { getContextApi } = useDynamic();<br><br>  useEffect(() =&gt; {<br>   <br>    var creator = window[plugin.libraryName!] as any;<br>    <br>    if (creator &amp;&amp; creator.default) {<br>      setComponent(creator);<br>    }<br>  }, []);<br><br>  const Plugin = React.lazy(() =&gt; {<br>    return Component ? Promise.resolve(Component) : Promise.resolve(() =&gt; {});<br>  });<br><br>  return (<br>    &lt;React.Suspense fallback={&lt;Spin tip=&quot;Plugin Uploading...&quot; /&gt;}&gt;<br>      {Component ? (<br>        &lt;Plugin useAuth={useAuth} getContextApi={getContextApi} /&gt;<br>      ) : (<br>        &lt;Spin tip=&quot;Plugin Uploading...&quot; /&gt;<br>      )}<br>    &lt;/React.Suspense&gt;<br>  );<br>};<br><br>export default React.memo(PluginViewer, (prev, next) =&gt; {<br>  return prev.libraryName === next.libraryName;<br>});</pre><p>Projenin kod örnekleri ve daha fazla ayrıntı için ilgili GitHub deposuna göz atabilirsiniz:</p><p><a href="https://github.com/mhmtyasr/react-dynamic-plugin-system">GitHub - mhmtyasr/react-dynamic-plugin-system</a></p><h3>LİVE VERSİON</h3><p><a href="https://react-dynamic-plugin-system-v2-1d5n.vercel.app/">Dynamic Layout and React Plugin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156a8c041ca8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>