Developing a Simple Taxonomy API using Node.js, Prisma ORM, and GraphQL for use with ODK

Developing a Simple Taxonomy API using Node.js, Prisma ORM, and GraphQL for use with ODK

A taxonomy API can be a small Node.js CRUD application that can run outside of your data collection application such as the Open Data Kit to provide you an API to call the keywords and post in ODK XML form schema.

Draft 1

Introduction

In the previous article, "Improve data quality in ODK using a standardized taxonomy", I argued for using a taxonomy service to improve data consistency for data collection efforts, such as those managed through Open Data Kit (ODK). Traditionally, ODK form developers don't use meaningful variables to name the data fields. For public surveys, CAPI tool developers have been using data fields like question1, question2, question3, etc. Most of the ODK projects create an ad-hoc taxonomy for use in their data collection efforts.

This article outlines a simple API for managing basic CRUD operations using Node.js, GraphQL, and Prisma ORM. The app uses PostgreSQL as the database.

Technology Stack

  1. Node.js - JavaScript runtime environment for server-side execution
  2. TypeScript - Typed superset of JavaScript that compiles to plain JavaScript
  3. GraphQL - Query language for APIs, providing flexible data fetching
  4. Prisma - Modern database ORM for Node.js & TypeScript with type safety
  5. PostgreSQL - Open-source relational database for data persistence
  6. Docker - Container platform for consistent development and deployment
  7. Apollo Server - GraphQL server that integrates with any GraphQL schema

Initialize project

Call this project capibuilder-keywords. In the directory, initialize the project:

npm init -y
npm install typescript @types/node ts-node --save-dev
npx tsc --init        

Install core dependencies

For this project, we are using the following core dependencies:

npm install @apollo/server graphql prisma @prisma/client        

Initialize Prisma

In the next step, we shall initialize the Prisma, a popular open-source ORM to manage the database. For this project, we are using the popular SQL database PostgreSQL.

npx prisma init        

For the database, we will use an external database. The database can be locally spun off using Docker or you can get the DATABASE_URL from any of the cloud providers. The database_url is declared in .env.

DATABASE_URL="postgresql://user:password@localhost:5432/keyworddb"        

For this project, we are following this structure:

src/

├── graphql/

│ └── modules/

│ └── keyword/

│ ├── keyword.resolvers.ts

│ └── keyword.typedefs.ts

├── middleware/

│ └── authMiddleware.ts

├── utils/

│ └── interface.ts

└── index.ts

Create base schema

In the schema.prisma file, create the following schema.

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Keyword {
  keywordId        String    @id @default(uuid())
  orgId            String
  keyword          String    @unique
  keywordTitle     String
  description      String?
  mainKeyword      Keyword?  @relation(name: "KeywordHierarchy", fields: [mainKeywordId], references: [keywordId])
  mainKeywordId    String?
  dataType         DataType?
  createdAt        DateTime  @default(now())
  updatedAt        DateTime  @updatedAt
  Keyword          Keyword[]
  Keyword          Keyword?  @relation(fields: [keywordKeywordId], references: [keywordId])
  keywordKeywordId String?

  @@index([keyword])
  @@index([keywordTitle])
  @@index([orgId])
}

enum VersionStatus {
  DRAFT
  RELEASED
  DEPRECATED
}

enum DataType {
  TEXT
  LONG_TEXT
  INTEGER
  DECIMAL
  FLOAT
  ARRAY
  OBJECT
  FILE
}        

The schema will allow us to create list of keywords. It will also allow us to maintain a parent-child relationship. Once the schema is created generate prisma client using

npx prisma generate        

If you run the migration using npx prisma migrate dev it will create the tables in the target database.

In the graphql folder, create 'keyword.typedefs.ts', 'keyword.resolvers.ts' and 'keyword.module.graphql.ts'. In the resolvers, you can create the key APIs:

  • getKeyword
  • getAllKeywords
  • createKeyword
  • updateKeyword
  • deleteKeyword

Once the graphql folder is created, you can generate the graphql types simply by installing graphql-codegen

# Install dependencies
npm install -D @graphql-codegen/cli @graphql-codegen/typescript
npm install -D @graphql-codegen/typescript-resolvers
npm install -D @graphql-codegen/typescript-operations        

GraphQL config file

# codegen.yml
schema: src/graphql/**/*.graphql
documents: null
generates:
  src/graphql/__generated__/graphql.ts:
    plugins:
      - typescript
      - typescript-resolvers
    config:
      contextType: ../../utils/interface#Context
      mappers:
        Keyword: '@prisma/client#Keyword'        

Then if you run npm run generate for the following NPM script, it will generate the graphql types.

{
  "scripts": {
    "generate": "graphql-codegen"
  }
}        

The code is available in capibuilder-keyword repository.

Very informative

回复

要查看或添加评论,请登录

Atanu Garai的更多文章

社区洞察

其他会员也浏览了