TypeScript

How to use PMKIN with TypeScript and Express

This guide demonstrates how to integrate PMKIN with your TypeScript and Express applications. All the code for this quick start guide is available in our TypeScript and Express quick start repository on GitHub.

Installation and Setup

Start by adding the necessary packages to your TypeScript and Express project:

npm install express @types/express pmkin dotenv

Set up your PMKIN API key as an environment variable. Create a .env file in your project root:

PMKIN_API_KEY=your_api_key_here

Project Structure

Create the following file structure:

src/
  ├── routes/
  │   ├── blog.ts
  │   └── blogPost.ts
  ├── pmkin.ts
  └── server.ts

Creating the Apollo Client

Create a new file src/pmkin.ts:

import dotenv from 'dotenv'
import { PmkinClient } from 'pmkin'

dotenv.config()

if (!process.env.PMKIN_API_KEY) {
  throw new Error('PMKIN_API_KEYis not set')
}

export const pmkin = new PmkinClient({
  token: process.env.PMKIN_API_KEY
})

Listing Documents

Create a new file src/routes/blog.ts:

import { Request, Response } from 'express'

import { pmkin } from '../pmkin'

export async function listBlogPostsHandler(request: Request, response: Response) {
  const posts = await pmkin.listDocuments()

  response.json({
    posts
  })
}

Show a Single Document

Create a new file src/routes/blog-post.ts:

import { Request, Response } from 'express'

import { pmkin } from '../pmkin'

export async function showBlogPostsHandler(request: Request, response: Response) {
  const post = await pmkin.findPostBySlug(
    decodeURIComponent(request.params.slug)
  )

  response.json({
    post
  })
}

Setting up the Express Server

Create a new file src/server.ts:

import express from 'express'

import { listBlogPostsHandler } from './routes/blog'
import { showBlogPostsHandler } from './routes/blog-post'

const app = express()
const port = process.env.PORT || 3000

app.get('/blog-posts', listBlogPostsHandler )
app.get('/blog-posts/:slug', showBlogPostsHandler )

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`)
})

Running the Application

To run your application, use the following command:

node src/server.ts

This setup provides a solid foundation for integrating PMKIN with your TypeScript and Express applications. Using PMKIN's API, you can expand on this by adding pagination, categories, or search functionality.