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 apollo-server-express @apollo/client graphql 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/
  ├── config/
  │   └── apollo-client.ts
  ├── routes/
  │   ├── blog.ts
  │   └── blogPost.ts
  ├── types/
  │   └── document.ts
  └── server.ts

Creating the Apollo Client

Create a new file src/config/apollo-client.ts:

import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import dotenv from 'dotenv'

dotenv.config()

const httpLink = createHttpLink({
  uri: 'https://content.pmkin.io/graphql'
})

const authLink = setContext((_, { headers }) => {
  const pmkinApiKey = process.env.PMKIN_API_KEY
  if (!pmkinApiKey) {
    throw new Error('PMKIN_API_KEY is not set.')
  }

  return {
    headers: {
      ...headers,
      authorization: `Bearer ${pmkinApiKey}`
    }
  }
})

export const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: authLink.concat(httpLink)
})

Define Document Type

Create a new file src/types/document.ts:

export interface Document {
  id: string
  metaDescription: string
  slug: string
  title: string
  markdown?: string
  metaTitle?: string
}

Listing Documents

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

Rendering Document Content

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

Setting up the Express Server

Create a new file src/server.ts:

import express from 'express'
import blogRoutes from './routes/blog'
import blogPostRoutes from './routes/blogPost'

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

app.use('/blog', blogRoutes)
app.use('/blog', blogPostRoutes)

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

Running the Application

To run your application, use the following command:

npx ts-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.