Skip to content

Nextjs + Prisma example #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2269631
added TS support and a backend support using sql-lite
joeynimu Jan 27, 2021
9d40e19
update schema
joeynimu Jan 27, 2021
91acdd9
feature: fetch category inventory/data from the backend
joeynimu Jan 27, 2021
5290b60
feature: single sku fetch from backend and only allow quantities avai…
joeynimu Jan 27, 2021
4e45097
update deps and untracked sqlite file
joeynimu Feb 4, 2021
ad58922
docs: added getting started docs
joeynimu Feb 4, 2021
c1dce4f
docs: added getting started docs
joeynimu Feb 4, 2021
0f97067
chore: ignore env file
joeynimu Feb 4, 2021
53d01d2
Merge pull request #1 from joeynimu/feature-prisma-backend
joeynimu Feb 4, 2021
9ce73fb
fix docs links
joeynimu Feb 4, 2021
76f1fb0
fix docs links
joeynimu Feb 4, 2021
c6776c8
docs: simplified docs
joeynimu Feb 4, 2021
d030460
typos
joeynimu Feb 4, 2021
e3e7b47
more typos
joeynimu Feb 4, 2021
f2a4ca4
update prisma and seeding script
joeynimu Feb 4, 2021
ac55e42
added backend for index/home and categories pages
joeynimu Mar 1, 2021
f180fde
Merge pull request #2 from joeynimu/feature-index-and-categories-pages
joeynimu Mar 1, 2021
09cb93f
es6 object omit
joeynimu Apr 20, 2021
1ab4c69
update dependancies
joeynimu Apr 20, 2021
f96b4aa
Merge pull request #3 from joeynimu/feature-index-and-categories-pages
joeynimu Apr 20, 2021
6d4a1c4
updates
joeynimu May 6, 2021
aefec4e
Merge branch 'feature-index-and-categories-pages' into next
joeynimu May 6, 2021
af0bc5a
Merge branch 'next' of github.com:joeynimu/jamstack-ecommerce into next
joeynimu May 6, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

#env files
.env
.env.local

# ignore sqlite db file
prisma/db
prisma/migrations/**

# dependencies
/node_modules
/.pnp
Expand All @@ -18,6 +26,7 @@
# misc
.DS_Store
*.pem
.vscode

# debug
npm-debug.log*
Expand Down
183 changes: 15 additions & 168 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,181 +1,28 @@
## Jamstack ECommerce Next

Jamstack ECommerce Next provides a way to quickly get up and running with a fully configurable ECommerce site using Next.js.
### Important!

Out of the box, the site uses completely static data coming from a provider at `providers/inventoryProvider.js`. You can update this provider to fetch data from any real API by changing the call in the `getInventory` function.
This is a fork from [Nader's Jamstack Ecommerce Next](https://github.com/jamstack-cms/jamstack-ecommerce). He has done all the work with setting up and building the UI among other things. This fork shows you how you can add a backend using Prisma using any supported database dialect.

![Home](example-images/1.png)
## Walkthrough/Tuitorial

### Live preview
If you prefer a walkthrough, I have written a [detailed blog post here](https://joeynimu.com/how-to-build-a-full-stack-jamstack-e-commerce-app-with-nextjs-and-prisma)

Click [here](https://www.jamstackecommerce.dev/) to see a live preview.
## Getting Started

<details>
<summary>Other Jamstack ECommerce pages</summary>
### Clone and Install Dependancies

### Category view
![Category view](example-images/2.png)
Start by cloning and installing dependancies.

### Item view
![Item view](example-images/3.png)
- `$ git clone https://github.com/joeynimu/jamstack-ecommerce.git`

### Cart view
![Cart view](example-images/4.png)
- `$ yarn` if you are using yarn or `$ npm install` if you are using npm

### Admin panel
![Admin panel](example-images/5.png)
</details>
- `$ yarn push-db`: Creates the db structure
- `$ yarn seed-db`: Adds some sample data for you to start with
- `$ yarn dev`: Runs the NexJS application that reads data from your database
- `$ yarn db-studio`: Opens Prisma Studio where you can view and edit your database

### Getting started
### Backend Details

1. Clone the project

```sh
$ git clone https://github.com/jamstack-cms/jamstack-ecommerce.git
```

2. Install the dependencies:

```sh
$ yarn

# or

$ npm install
```

3. Run the project

```sh
$ npm run dev

# or to build

$ npm run build
```

## Deploy to Vercel

Use the [Vercel CLI](https://vercel.com/download)

```sh
vercel
```

## Deploy to AWS

```sh
npx serverless
```

## About the project

### Tailwind

This project is styled using Tailwind. To learn more how this works, check out the Tailwind documentation [here](https://tailwindcss.com/docs).

### Components

The main files, components, and images you may want to change / modify are:

__Logo__ - public/logo.png
__Button, ListItem, etc..__ - components
__Form components__ - components/formComponents
__Context (state)__ - context/mainContext.js
__Pages (admin, cart, checkout, index)__ - pages
__Templates (category view, single item view, inventory views)__ - templates

### How it works

As it is set up, inventory is fetched from a local hard coded array of inventory items. This can easily be configured to instead be fetched from a remote source like Shopify or another CMS or data source by changing the inventory provider.

#### Configuring inventory provider

Update __utils/inventoryProvider.js__ with your own inventory provider.

#### Download images at build time

If you change the provider to fetch images from a remote source, you may choose to also download the images locally at build time to improve performance. Here is an example of some code that should work for this use case:

```javascript
import fs from 'fs'
import axios from 'axios'
import path from 'path'

function getImageKey(url) {
const split = url.split('/')
const key = split[split.length - 1]
const keyItems = key.split('?')
const imageKey = keyItems[0]
return imageKey
}

function getPathName(url, pathName = 'downloads') {
let reqPath = path.join(__dirname, '..')
let key = getImageKey(url)
key = key.replace(/%/g, "")
const rawPath = `${reqPath}/public/${pathName}/${key}`
return rawPath
}

async function downloadImage (url) {
return new Promise(async (resolve, reject) => {
const path = getPathName(url)
const writer = fs.createWriteStream(path)
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
})
response.data.pipe(writer)
writer.on('finish', resolve)
writer.on('error', reject)
})
}

export default downloadImage
```

You can use this function to map over the inventory data after fetching and replace the image paths with a reference to the location of the downloaded images, probably would look something like this:

```javascript
await Promise.all(
inventory.map(async (item, index) => {
try {
const relativeUrl = `../downloads/${item.image}`
if (!fs.existsSync(`${__dirname}/public/downloads/${item.image}`)) {
await downloadImage(image)
}
inventory[index].image = relativeUrl
} catch (err) {
console.log('error downloading image: ', err)
}
})
)
```

### Updating with Auth / Admin panel

1. Update __pages/admin.js__ with sign up, sign, in, sign out, and confirm sign in methods.

2. Update __components/ViewInventory.js__ with methods to interact with the actual inventory API.

3. Update __components/formComponents/AddInventory.js__ with methods to add item to actual inventory API.

### Roadmap

- Full product and category search
- Auto dropdown navigation for large number of categories
- Ability to add more / more configurable metadata to item details
- Themeing + dark mode
- Optional user account / profiles out of the box
- Make Admin Panel responsive
- Have an idea or a request? Submit [an issue](https://github.com/jamstack-cms/jamstack-ecommerce/issues) or [a pull request](https://github.com/jamstack-cms/jamstack-ecommerce/pulls)!

### Other considerations

#### Server-side processing of payments

To see an example of how to process payments server-side with stripe, check out the [Lambda function in the snippets folder](https://github.com/jamstack-cms/jamstack-ecommerce/blob/next/snippets/lambda.js).

Also, consider verifying totals by passing in an array of IDs into the function, calculating the total on the server, then comparing the totals to check and make sure they match.
By default, the project is configured to use `sqlite` but you can change this to point to a `PostgreSQL` db instance or any other supported dialect.
4 changes: 4 additions & 0 deletions lib/prisma-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient()
export default prisma
2 changes: 2 additions & 0 deletions next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/// <reference types="next" />
/// <reference types="next/types/global" />
14 changes: 13 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
"start": "next start",
"generate": "npx prisma generate",
"push-db": "npx prisma db push --preview-feature",
"seed-db": "npx prisma db seed --preview-feature",
"db-studio": "npx prisma studio"
},
"dependencies": {
"@prisma/client": "^2.21.2",
"@stripe/react-stripe-js": "^1.1.2",
"@stripe/stripe-js": "^1.11.0",
"@types/react": "^17.0.2",
"autoprefixer": "^10.1.0",
"next": "10.0.4",
"postcss": "^8.2.2",
Expand All @@ -19,5 +25,11 @@
"react-toastify": "^6.2.0",
"tailwindcss": "^2.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/node": "^14.14.41",
"prisma": "^2.21.2",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
}
}
74 changes: 0 additions & 74 deletions pages/categories.js

This file was deleted.

Loading