Integrate Hygraph with Svelte, React, Vue

Hygraph headless CMS integration samples


Graph CMS or Hygraph CMS is a headless CMS for building backend for web and mobile apps. It is easy to use.

The Graphql which is modern way to fetch selected part of a database, enable developers to easily access the data in Hygraph.

Integrate Hygraph with Svelte

The first step is to enable public API from the Hygraph settings and then we can use libraries like urql, apollo, graphql-request for querying data.

In the Svelte Kit route we can place a load module on the top of the component for fetching data as follows .

//route/index.svelte

<script context="module">
    import {GraphQLClient} from "graphql-request";
    export async function load({params}) {
        const {slug} = params;
        const graphcms = new GraphQLClient(
            'https://api-ap-south-1.hygraph.com/v2/cl5uo7orr3kf801t8d4ld7hoe/master',
            {
                headers: {},
            }
        )
        const data = await graphcms.request(
            `query  {
        blogpost(where: {slug: "${slug}"})
        {
            title
            catgory
            content{
            html
            }
            publishedAt
            summary
            image {
            fileName
            url
        }
        }
    }`
        );
 return{
     props: {
         post: data.blogpost,
     },
 }
    }

</script>

<script>
    export let post;

</script> 

Similarly we can apply the logic on Angular Service, Vuejs, React, and Solidjs.

I have two projects on Github for you 🎦

Integrate Contentful in Vue 3


Integrate Contentful CMS in Vue 3, can be done using Graphql as well as the contentful library. We go with npm package.

Install the dependency by running the command yarn add contentful in terminal.

The client

We can a create client module in order to make contentful queries.

//contentdul/index.js

import {createClient} from 'contentful'

const client=createClient({
    space:'w591jyzdi2py',
    accessToken:'DXG7DohnxRncpcxSPtLGr5fR4_fzjyzRzVZAiP9Ussk'
});

export {client}  

Replace the space and accessToken with your Contentful configurations which can be accessible in settings (contentful.com).

A list of posts

Using the getEntries async methos we can fetch the entries object. Since it is a an async call, we have to use a async component.

So lets create a list of posts

<template>
  <div>
    <h3> Contentful entries are ...</h3>
    <ol v-for="post in posts.items">
      <router-link :to="{path:`/post/${post.sys.id}`}">
        <ul>{{ post.fields.title }}</ul>
      </router-link>
    </ol>
  </div>
</template>

<script setup lang="ts">
import {client} from '@/contentful'
const posts = await client.getEntries();
</script>

<style scoped>

</style> 

The above setup component is an async component since it has a top level await.

Render the list

In a View component , we can render the async component with optional fall back template.

<script setup lang="ts">
import PostList from '@/components/PostList.vue'
</script>
<template>
  <div>
    <h1>Posts</h1>
    <suspense>
      <post-list/>
      <template #fallback>
        loading ..
      </template>
    </suspense>
  </div>
</template>
 

The same logic can be applied to a dynamic route. Please using dynamic route guide for Vue 3.

[display-post id=8704]

How to build a blog using Nuxt 3 and Graphql

How to build a blog app using TailwindCSS + Nuxt 3 + Graphql API


Vue is so popular among UI developers and also among React users. It is easy to learn and develop apps required with minimal effort.

Vue 3 is the latest version and Nuxt 3 is another framework on top Vue 3 with lots build tools.

Nuxt 3 come with all required tool for full stack developer and API route, middleware, plugins etc.

Here is our full live Nuxt 3 blog project

Continue reading “How to build a blog using Nuxt 3 and Graphql”

Editor frameworks for JS apps

About Javascript Editor frameworks


If you are building content based application such as blog, may want featured editor, such as Post editor or comment box. Making such an editor with all formatting capabilities would be tiresome.

Editor frameworks and wrapper libraries help us achieve this goal with ease and peace. I don’t intended to review each of these , instead I would to list best of them and in the up coming posts we will learn using these awesome editor frameworks.

My Picks

I like block editor mostly for content management, in my react app I will choose the Editor.js . It is easy to configure and use.

Second most useful framework for content management is Drftjs , which is maintained by Facebook itself. It is a complete Editor framework featuring mention, hashtag etc and it’s flexible too.

Here is complete list of framework available for building a full featured editor in your next JS / React/Vue/Angular app

Prisma MongoDB connection

How to configure MongoDB (local and Cloud based ) in Prisma ORM


Prisma is a Typescript based ORM for Javascript Frameworks such as React, Vuejs and Angular. It allows developers easily configure database and hand data using model classes.

Mongo DB

MongoDB is a NoSQL database for web, primarily. It is widely used in cloud based web and Mobile application.

How to configure MongoDB on Prima

In Prisma configuration file we can use preview version on MongoDB driver. The connection string can be stored in .env file (at the route of your project).

Local database

Form local database we can use the following connection string

//.env
 DATABASE_URL = mongodb://localhost:27017/blogdata?retryWrites=true&w=majority

Mongo Atlas database

For cloud based Mongo database we have to rely on the following connection.

//.env
 DATABASE_URL = mongodb+srv://admin:RRHEfMsK8zHWsGTI@cluster0.cqnll.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

schema.prisma

Finally the Prisma Schema file would look like the following,

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

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["mongodb"]
}

model User {

  id    String @id @default(auto()) @map("_id") @db.ObjectId

  email String

} 

Migrating DB

If you are familiar with Prisma and Schema, we used to run migrate command to update the database with model.

There is an exception for Mongo, you don’t need to Migrate, instead run npx prisma generate command after any change made to schema.

To update the model we use npx prisma db push command.

How to create build tool enabled Vue project in 10 second

How to create a build tool enabled Vue project in 10 second


Build tool allows us to quickly setup a vuejs project. All you have to do is install Vuejs on development machine and do the following

Initialize

> npm init vue@latest

This will ask few things like

✔ Project name: … <your-project-name>
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add Cypress for both Unit and End-to-End testing? … No / Yes
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes

Simply furnish the details and the project scaffold will be generate in seconds.

Install dependencies

Now time to install the dependencies, let’s run

npm run install 
or
yarn install

Running the project

Let’s run the project and see what you got

Prismic-CMS-Nuxt slice rendering

Prismic-CMS-Nuxt slice rendering example


This is a Prismic-CMS-Nuxt slice rendering example

<template>
<div class="container">
<div class="flex">
<slice-zone class="subtitle"
:slices="page.data.body1"
:resolver="resolver" />
</div>
</div>
</template>
<script>
import SliceZone from "vue-slicezone";
import * as Slices from "@/slices";
export default {
mounted() {},
async asyncData({ $prismic }) {
return {
page: await $prismic.api.getSingle("home"),
};
},
components: {
SliceZone,
},
data() {
return {
};
},
methods: {
resolver({ sliceName, slice, i }) {
return Slices[sliceName];
},
},
};
</script>

Prismic-CMS-Nuxt store

Prismic-CMS-Nuxt store example


This is a Prismic-CMS-Nuxt store example

export const state = () => ({
snippets: Object,
isLoaded: false,
})
export const actions = {
async loadSnippets({ commit }) {
const document = await this.$prismic.api.query(
this.$prismic.predicates.at("document.type", "snippet_type")
);
commit('setSnippet', document);
commit('setLoaded', true);
}
}
export const mutations = {
setSnippet(state, code) {
state.snippets = code
},
setLoaded(state, loaded) {
state.isLoaded = loaded
}
}

Vue Tag snippet

Vue Tag (Google Analytic) implementation snippet


This is a Vue Tag implementation snippet

import Vue from "vue";
import VueGtag from "vue-gtag";
Vue.use(VueGtag, {
config: { id: process.env.GID}, //measurement ID G-LL1HBDMH8D,
params: {
send_page_view: false
}
});
view raw Vue-analytic.js hosted with ❤ by GitHub

Nuxt apollo-graphql server with Apollo and Express

Nuxt apollo-graphql server with Apollo, Express, and Prisma using serverMiddleware


This is a JavaScript snippet for implementing apollo-graphql server with Apollo in Nuxt 2

/* Create a folder , api/graphql.ts (root of peoject) and paste the following code*/
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const {PrismaClient} = require("@prisma/client")
const prisma = new PrismaClient();
const typeDefs = gql`
type Todo{
item:String!,
id:String
}
type Query{
getAll: [Todo!]!
}
type Mutation{
newTodo(item :String!):Todo
}
`;
const resolvers = {
Query: {
getAll() {
return prisma.todo.findMany();
}
},
Mutation: {
async newTodo(_parent: any, _args: any) {
const newTodo = await prisma.todo.create({
data:_args
});
return newTodo;
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers
});
const app = express();
server.start().then((r: any) => {
server.applyMiddleware({ app });
});
export default {
path: "/api",
handler: app
};
/* Add a middle ware in Nuxt-config*/
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
serverMiddleware:[
'~/api/graphql.ts'
] ,
...
view raw graphql.ts hosted with ❤ by GitHub

On GitHub , All Gits