Express.js ile Prisma kullanımı

Herkese merhaba bu yazımda günümüzde oldukça popüler bir stack haline gelmiş Node.js (Express) ve Prisma ORM kullanımını anlatmaya çalışacağım özellikle daha önce ORM kullanmamış ve Plain text SQL yazmaya mahkum olmuş dostlarım için elimden geldiğince bir rehber niteliğinde olmasını sağlayacağım. Mutlaka eksik veya atladığım kısımlar olabilir. Lütfen bana bu kısımları bildirmeyi unutmayın.. Keyifli okumalar :)

captionless image

Prisma Nedir? Diğer ORM Araçları

Prisma her ne kadar isim olarak oldukça havalı dursada aslında çok öncesinde bir çok iyi, kötü örnekleri bulunan bir ORM yani Object Relation Mapping araçlarından biri diyebiliriz. Alternatifleri olarak ise TypeORM, Sequelize, Drizzle ORM gibi alternatiflerini sunabiliriz. Bu arkadaşlar her ne kadar temelde aynı işleri yapmak için hayata geçirilmiş olsalarda tabi ki lifecycle olarak hepsi birbirinden farklı haraket ediyor. Aralarında ki avantajlı, dezavantajlı yönleri bir kenara bırakalım. Şu an da, Prisma özellikle TypeScript, JavaScript topluluğunda çok önemli bir yere sahip. Bunun hemen arkasından ise Drizzle performansı ile göz dolduruyor gibi duruyor hangisini kullanıp kullanmamak size kalmış avantajlarını ve dezavantajlarını iyice araştırıp ihtiyacınıza göre projelerinizde kullanabilirsiniz. Bizim bugün ki konumuz ise tabi ki Prisma.

Prismayı daha detaylı bir şekilde ele almamız gerekirse veri tabanı sorgularınızı kolaylaştıran ve veritabanı yönetimizi daha verimli hale getiren ORM aracı diyebiliriz. Prisma hakkında detaylı bilgiye ve dökümantasyona buradan ulaşabilirsiniz.

Prismanın Temel Özellikleri nelerdir?

Prisma modern bir ORM aracı olarak otomatik şema oluşturma, Tip güvenliği, veritabanı sorgularının basitleştirilmesi bir çok özellikle beraberinde geliyor. Her ne kadar çok fazla kullanmaya ihtiyaç duymasamda veritabanı datalarını kolayca görüntüleyebilmemizi sağlayan Prisma Studio ile de beraber geliyor. Özellikle 5.0 sürümü ile performans konusunda da çok önemli bir artış sağlanmış. Nedir bu tip güvenliği (Type Safety) derseniz o konuya da değinmeden geçmeyelim.

Type Safety bir programlama dilinin örneğimizde TypeScript, değişkenlerinin, fonksiyonlarının beklenen veri türlerini kullanması ve yalnızca uyumlu işlemlerin bu türler üzerinde yapılmasını sağlamak anlamına gelir. Konumuzdan sapmamak için çok detay bilgiye girmeyeceğim efenim fakat bıraktığım kaynakları inceleyip daha detaylı bilgi sahibi olabilirsiniz.

Daha detaylı bilgi için bu kaynaklara göz atabilirsiniz.

Type Safety (Tip — Tür Güvenliği)

Type Safety and strong Typing

Type Safety (Prisma)

Teorik olarak konuyu yeterince açıkladık sanırsam detay olarak bir çok daha detaydan bahsedebiliriz. Özellikle Prisma feature olarak çok fazla yeni preview özellik barındırıyor fakat dediğim gibi konudan pek fazla sapmayalım ve teoriden ziyade Express.js uygulamamız üzerinden Prisma kullanarak PostgreSQL veritabanımıza bağlanıp gerekli migration komutlarımızı çalıştıralım. Bu noktada sakin olmanızı istiyorum çünkü bütün proje kodlarını makale sonunda github adresim üzerinden ulaşabilirsiniz :)

Öncelikle TypeScript ile Express projemizi oluşturalım

Ben paket yöneticisi olarak pnpm kullanacağım siz npm yada yarn’da kullanabilirsiniz. “pnpm” hakkında daha detaylı bilgi için

Sırası ile

pnpm init
tsc --init

komutlarımızı çalıştıralım “pnpm init” komutumuz package.json dosyamızı projemize oluşturacak. “tsc — init” komutumuz ise tsconfig.json dosyamızı projemize init etmiş olacak. tsconfig.json dosyası için ben bu şekilde bir yapılandırma kullanıyorum sizler farklı configurasyon ayarları kullanabilirsiniz. Bu yapılandırma ile “src” içerisinde yazdığımız TypeScript kodumuzu “dist” klasörümüze compile edeceğiz.

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */
    /* Projects */
    "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
    /* Language and Environment */
    "target": "ES6",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
    "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */
    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "./src",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
    // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
    // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
    // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

Buraya kadar her şey tamam ise artık gerekli npm paketlerimizi uygulamamıza yükleyelim çok detaylı bir proje yapmayacağımız için öncelikle Expressi ve gerekli paketlerimizi yükleyebiliriz. Projede kullandığım npm paketlerini tek bir komut halinde sizlere verebilirim

sudo pnpm add express @prisma/client bcryptjs compression cookie-parser cors cross-env dotenv helmet

Evet bu şekilde uzunca bir pnpm add komutu ile gerekli paketlerimizi ekledik burada ki paketlerin hangi işlevleri sağladığını burada açıklamayacağım her hangi bir paket hakkında internette bir çok kaynak bulabilirsiniz. Bu işlemden sonra tabi ki projemiz TypeScript olduğu için Type definitionları da kurmayı unutmayalım.

Dipnot: Node.js 20 üzeri sürümlerde dotenv kullanmanıza gerek yok. Ben burada örnek olsun diye kullanmayı tercih ettim açıkcası detaylı bilgi

sudo pnpm add --save-dev @types/express prisma ts-node typescript @types/compression @types/cookie-parser @types/cors @types/node

İlk defa projelerinde TypeScript kulanacak arkadaşlar için her npm paketinin type definitionlarını kurmamıza gerek yok bir çok güncel paket kendi type definionları ile birlikte geliyor. En sağlıklı bilgi için mutlaka ziyaret edelim ve tabi ki MacOs veya Linux kullanmıyorsunuz sudo gerek yok :)

Projemizin dosya yapısını oluşturalım dilerseniz. Bu şekilde bir project structure oluşturdum.

captionless image

Bu express uygulamasında “app.ts” dosya yapılandırmam bu şekilde

captionless image

Bu işlemden önce .env dosyamızı oluşturalım ve config.ts dosyamız içerisine gerekli environment ayarlarımızı yapılandıralım. Uygulamanın port bilgisi, database connection url gibi bilgileri yapılandıralım. Son halimiz bu şekilde

captionless image

Database olarak Railway uzak sunucumda ki PostgreSQL veritabanımı kullandım siz dilerseniz local kullanabilir veya benim gibi her hangi bir cloud hizmetinden yararlanabilirsiniz.

captionless image

Buraya kadar geldik ise artık yapacaklarımız gerçekten basit Prisma bizim için bir çok işlemi oldukça kolaylaştırıyor diyebiliriz.

npx prisma init --datasource-provider postgresql

Bu komut bizim için postgresql providerını kullanarak prisma için model dosyamızı projemizin ana klasörüne oluşturacak terminalda bakmamız gerekirse

captionless image

Bu komutu çalıştırdığımız zaman Prisma bizim için “schema.prisma” için modellerimizi tanımlayacağımız bir schema dosyası yaratmış oluyor. Uygulamamızın bütün modellerini ve database ilişkilerini burada tanımlayacağız.

captionless image

Burada öncelikle bir User modeli tanımlayalım ve PostgreSQL veritabanımıza gerekli migration işlemini yapalım Prisma bizim için migration işlemini gerçekleştirip tanımladığımız tablolarımızı ve kolonlarımızı veritabanı içerisine oluşturacak.

captionless image

Burada bir “User” modeli oluşturuyoruz buradaki alanları ve keywordları Prisma’nın dökümanından detaylı bir şekilde öğrenebilirsiniz. Özellikle tablolar arasında ki ilişkileri Prisma sayesinde oldukça kolay bir şekilde halledebilirsiniz.

“User” modelimi oluşturduktan sonra ise migration kodumuzu çalıştırabiliriz artık. Prisma bizim için veritabanımıza gidip gerekli tabloları yaratacak.

sudo npx prisma migrate dev --name init

burada “ — name init” ise bu migrationımıza verdiğimiz isim. Bir süre bekledikten sonra bu şekilde bir ekran görüyor iseniz migration işlemimiz tamam demektir :)

captionless image

Evet artık nerdeyse Prisma ile gerekli migration işlemlerini tamamlayıp örnek bir PostgreSQL database oluşturmuş olduk artık dilerseniz. Basit bir “GetAllUsers” API yazıp bu methodumuzu test edelim..

captionless image

Basit bir API yazarak Prisma ile oluşturmuş olduğumuz database içerisin deki alanlarımızı sorgulayabildik. Gerekli bütün kodları ise yazının sonunda ki github reposu üzerinden bulabilirsiniz. Eksik taraflarımı lütfen bana bildirin efenim umarım yararlı bir makale olmuştur. Bir sonra ki yazıda görüşmek üzere..

Github Reposu