Skip to content
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

merge #1

Merged
merged 27 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
54e0c02
feat: add Register template
AprilChoiAFO Aug 8, 2024
26cffe1
Update runtime
AprilChoiAFO Aug 8, 2024
5ec29a3
Update runtime
AprilChoiAFO Aug 8, 2024
66e112c
Update config name
AprilChoiAFO Aug 8, 2024
ca93451
add helloworld functions api
AprilChoiAFO Aug 9, 2024
e661aca
Merge pull request #1 from AprilChoiAFO/development
AprilChoiAFO Aug 9, 2024
f1d7fce
added helloworld functions
AprilChoiAFO Aug 9, 2024
4f9a7b3
delete .wrangler
AprilChoiAFO Aug 9, 2024
d2c7f49
trying to fix yarn
AprilChoiAFO Aug 9, 2024
0ee24bb
trying to fix yarn
AprilChoiAFO Aug 9, 2024
f7fa560
update wrangler
AprilChoiAFO Aug 9, 2024
4fb3c76
- added cloudflare/next-on-pages as default build - set up api using…
AprilChoiAFO Aug 9, 2024
a9a6611
fix package.json cloudflare local build
AprilChoiAFO Aug 9, 2024
18b213f
FEAT: set form get value from api
AprilChoiAFO Aug 9, 2024
e67d958
try deploy on and see if can read DB
AprilChoiAFO Aug 12, 2024
6cd7c0b
add DB into env
AprilChoiAFO Aug 12, 2024
9142707
add .env file
AprilChoiAFO Aug 12, 2024
d206e1b
trying to fix variable
AprilChoiAFO Aug 12, 2024
40cb978
changed compactivility date and change env
AprilChoiAFO Aug 12, 2024
7ccb591
changed compactivility date and change env
AprilChoiAFO Aug 12, 2024
d15cabd
updated compactivity date
AprilChoiAFO Aug 12, 2024
40af282
Update env package fixed env import
AprilChoiAFO Aug 13, 2024
79e5217
update field_name and field_type
AprilChoiAFO Aug 13, 2024
e9122e7
update submit route
AprilChoiAFO Aug 13, 2024
fa7a1c6
update api
AprilChoiAFO Aug 14, 2024
bff5513
fix type4
AprilChoiAFO Aug 14, 2024
0d126d3
fix type
AprilChoiAFO Aug 14, 2024
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
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,7 @@ next-env.d.ts
# next-sitemap
robots.txt
sitemap.xml
sitemap-*.xml
sitemap-*.xml

#cloudfare
.wrangler/*
10 changes: 10 additions & 0 deletions env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { loadEnvConfig } from '@next/env'

const projectDir = process.cwd()
loadEnvConfig(projectDir)

declare global {
interface CloudflareEnv {
DB: D1Database
}
}
1 change: 0 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ const createJestConfig = nextJest({
const customJestConfig = {
// Add more setup options before each test is run
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],

// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'],

Expand Down
23 changes: 23 additions & 0 deletions migrations/0001_form_fields.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- Migration number: 0001 2024-08-12T08:14:43.040Z


create table form_fields (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id integer not null,
field_name varchar(255) not null,
field_type varchar(255) not null,
field_order integer not null,
created_at timestamp not null default current_timestamp,
updated_at timestamp not null default current_timestamp
);

create table responses(
id INTEGER PRIMARY KEY AUTOINCREMENT,
response text not null
);

INSERT INTO form_fields (form_id, field_name, field_type, field_order)
VALUES
(1, 'Name', 'text', 1),
(1, 'Email', 'email', 2),
(1, 'Age', 'number', 3);
4 changes: 4 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
/** @type {import('next').NextConfig} */
const { setupDevPlatform } = require('@cloudflare/next-on-pages/next-dev');
if (process.env.NODE_ENV === 'development') {
setupDevPlatform();
}
const nextConfig = {
eslint: {
dirs: ['src'],
Expand Down
24 changes: 18 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "nextjs-materia-mui-typescript-hook-form-scaffold-boilerplate-starter",
"name": "template",
"version": "0.1.0",
"private": true,
"scripts": {
Expand All @@ -15,23 +15,34 @@
"format": "prettier -w .",
"format:check": "prettier -c .",
"postbuild": "next-sitemap --config next-sitemap.config.js",
"prepare": "husky install"
"prepare": "husky install",
"api": "wrangler pages dev .",
"cloudflare-start": " npx wrangler pages dev .vercel/output/static",
"apply-d1-remote": "wrangler d1 migrations apply template-demo --remote",
"pages:build": "npx @cloudflare/next-on-pages",
"preview": "npm run pages:build && wrangler pages dev",
"deploy": "npm run pages:build && wrangler pages deploy"
},
"dependencies": {
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@hookform/resolvers": "^3.3.1",
"@mui/icons-material": "^5.14.9",
"@mui/material": "^5.14.10",
"@next/env": "^14.2.5",
"@types/node": "^22.2.0",
"dayjs": "^1.11.10",
"next": "^14.0.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.46.2",
"react-icons": "^4.10.1",
"wrangler": "^3.70.0",
"zod": "^3.22.4"
},
"devDependencies": {
"@cloudflare/next-on-pages": "^1.13.2",
"@cloudflare/workers-types": "^4.20240806.0",
"@commitlint/cli": "^16.3.0",
"@commitlint/config-conventional": "^16.2.4",
"@svgr/webpack": "^8.0.1",
Expand All @@ -53,15 +64,16 @@
"next-sitemap": "^2.5.28",
"postcss": "^8.4.26",
"prettier": "^2.8.8",
"typescript": "^4.9.5"
"typescript": "^4.9.5",
"vercel": "^35.2.4"
},
"lint-staged": {
"**/*.{js,jsx,ts,tsx}": [
"eslint --max-warnings=0",
"prettier -w"
],
"**/*.{json,css,scss,md,webmanifest}": [
"prettier -w"
]
}
}
},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
17 changes: 17 additions & 0 deletions src/app/api/getform/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const runtime = 'edge';
import { D1Database } from '@cloudflare/workers-types'
import { NextResponse } from 'next/server';

export interface Env {
DB: D1Database;
}
import { getRequestContext } from '@cloudflare/next-on-pages'


export async function GET() {
const { env } = getRequestContext()
const myDb = env.DB;
const data: any = await myDb.prepare('SELECT * FROM form_fields').all();

Check warning on line 14 in src/app/api/getform/route.ts

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

Unexpected any. Specify a different type

return NextResponse.json(data.results);
}
7 changes: 7 additions & 0 deletions src/app/api/getform/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export type FormFieldRow = {
form_field_id: number;
form_id: number;
field_name: string;
field_type: string;
field_order: number;
};
41 changes: 41 additions & 0 deletions src/app/api/submitForm/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export const runtime = 'edge';
import { D1Database } from '@cloudflare/workers-types'

Check warning on line 2 in src/app/api/submitForm/route.ts

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

Run autofix to sort these imports!
import { NextRequest, NextResponse } from 'next/server';
import { SubmitForm } from '@/app/api/submitForm/types';
export interface Env {
DB: D1Database;
}
import { getRequestContext } from '@cloudflare/next-on-pages'


export async function POST(req: NextRequest) {

const { env } = getRequestContext()
const myDb = env.DB;

try {
// Get JSON data from the POST request body
const data = await req.json();
console.log('Received data:', data);

Check warning on line 19 in src/app/api/submitForm/route.ts

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

Unexpected console statement
// Assuming data is an array of objects with { key, value }
const entriesArray = (data as SubmitForm[]).map(({ Field, Value }) => `${Value}`);

Check warning on line 21 in src/app/api/submitForm/route.ts

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

'Field' is defined but never used. Allowed unused args must match /^_/u
console.log(entriesArray);

Check warning on line 22 in src/app/api/submitForm/route.ts

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

Unexpected console statement

// Construct the SQL statement
let stmt = "INSERT INTO responses (response) VALUES ";
const values = entriesArray.map(value => `('${value}')`).join(", ");
stmt += values + ";";

// Process the data as needed
console.log('Executing SQL statement:', stmt);

Check warning on line 30 in src/app/api/submitForm/route.ts

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

Unexpected console statement
const res = await myDb.prepare(stmt).run();

// Send a response back to the client
return NextResponse.json({ message: 'Data received successfully', data, res });
} catch (error) {
console.error('Error processing POST request:', error);

Check warning on line 36 in src/app/api/submitForm/route.ts

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

Unexpected console statement
return NextResponse.json({ message: 'Internal Server Error' }, { status: 500 });
}


}
4 changes: 4 additions & 0 deletions src/app/api/submitForm/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type SubmitForm = {
Field: string;
Value: string;
};
31 changes: 10 additions & 21 deletions src/app/api/test/route.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
import { NextResponse } from 'next/server';

// Test local NextJs API /api/test method GET with parameters
export const GET = async (req: Request) => {
const { searchParams } = new URL(req.url);
const reqData = Object.fromEntries(searchParams);
return NextResponse.json({
message: 'Test getApiResponse GET success!',
method: 'GET',
reqData,
});
};

// Test local NextJs API /api/test method POST with variables
export const POST = async (req: Request) => {
const reqData = await req.json();
return NextResponse.json({
message: 'Test postApiResponse POST success!',
method: 'POST',
reqData,
});
};
export const runtime = 'edge';
export const GET = async () => {
return NextResponse.json([
{ field_name: 'Name', field_type: 'text' },
{ field_name: 'Email', field_type: 'email' },
{ field_name: 'Organization', field_type: 'text' },
{ field_name: 'Surname', field_type: 'text' },
{ field_name: 'Field', field_type: 'text' },
]);
};
1 change: 0 additions & 1 deletion src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import * as React from 'react';

import { SITE_CONFIG } from '@/constants';
import { GLOBAL_STYLES } from '@/styles';

// !STARTERCONF Change these default meta
// !STARTERCONF Look at @/constant/config to change them
export const metadata: Metadata = {
Expand Down
2 changes: 2 additions & 0 deletions src/app/not-found.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Metadata } from 'next';
import * as React from 'react';
import { RiAlarmWarningFill } from 'react-icons/ri';

export const runtime = 'edge'

export const metadata: Metadata = {
title: 'Not Found',
};
Expand Down
24 changes: 13 additions & 11 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import Homepage from '@/components/Homepage';
import { Box } from '@mui/material';

import { getApiResponse } from '@/utils/shared/get-api-response';

import { NpmData, PageParams } from '@/types';
import Register from '@/components/Register';
import SignIn from '@/components/Signin';

Check warning on line 4 in src/app/page.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

'SignIn' is defined but never used

//import { PageParams } from '@/types';
/*
const loadDataFromApi = async (slug?: string) => {
if (slug === 'testError500') {
throw new Error('This is mock a ssr 500 test error');
Expand All @@ -28,16 +29,17 @@
nextJsNpmData,
};
};
*/
//const AppHome = async ({ searchParams }: PageParams) => {

const AppHome = async ({ searchParams }: PageParams) => {
const slug = searchParams?.slug;
const { reactNpmData, nextJsNpmData } = await loadDataFromApi(slug);
const AppHome = async () => {
//const slug = searchParams?.slug;
//const { reactNpmData, nextJsNpmData } = await loadDataFromApi(slug);

return (
<Homepage
reactVersion={reactNpmData?.version}
nextJsVersion={nextJsNpmData?.version}
/>
<Box>
<Register />
</Box>
);
};

Expand Down
86 changes: 86 additions & 0 deletions src/components/Register.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
'use client';
import { Button, Checkbox, FormControl, TextField, Box } from '@mui/material';

Check warning on line 2 in src/components/Register.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

Run autofix to sort these imports!

Check warning on line 2 in src/components/Register.tsx

View workflow job for this annotation

GitHub Actions / ⬣ ESLint, ʦ TypeScript, 💅 Prettier, and 🃏 Test

'FormControl' is defined but never used
//import Container from '@mui/material';
//import { FormControl } from '@mui/material';
import Grid from '@mui/material/Grid';
import React, { useEffect, useState } from 'react';
interface Field {

field_name: string;
field_type: string;
}

const Register: React.FC = () => {
const [fields, setFields] = useState<Field[]>();;

const [formValues, setFormValues] = useState<Map<string, string>>(new Map());
const [agree, setAgree] = useState(false);

useEffect(() => {
// Fetch API result and update fields state
fetch('/api/getform')
.then((response) => response.json())
.then((data) => setFields(data as Field[]));
}, []);

const handleInputChange = (label: string, value: string) => {
setFormValues((prevValues: Map<string, string>) => {
prevValues.set(label, value);
return prevValues;
});
};

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const entriesArray = Array.from(formValues.entries()).map(([key, value]) => ({ Field: key, Value: value }));
console.log('Submitting form:', formValues);
try {
const response = await fetch('/api/submitForm', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(entriesArray)
});

const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error submitting form:', error);
}
};

return (
<Grid
container
direction='column'
justifyContent='center'
alignItems='center'
>
<Box component='form' onSubmit={handleSubmit} noValidate alignItems='center'>
{fields?.map((field, index) => (
<Grid item xs key={index}>
<TextField
key={index}
label={field.field_name}
type={field.field_type}
fullWidth
margin='normal'
onChange={(e) => handleInputChange(field.field_name, e.target.value)}
/>
</Grid>
))}
<Grid item xs>
<Checkbox checked={agree} onChange={(e) => setAgree(e.target.checked)} />
</Grid>
<Grid item xs>
<Button variant='contained' color='primary' type='submit'>
Register
</Button>
</Grid>
</Box>
</Grid>
);
};

export default Register;
Loading
Loading