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

[DEMO] - Implementing backend on Next.JS that sets cookies and a mini GraphQL server #35

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
70 changes: 35 additions & 35 deletions __tests__/pages/signup.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,45 +31,45 @@ describe('Signup Page', () => {
const lastNameField = getByTestId('lastName')
const submitButton = getByTestId('submit')

await wait(
() =>
fireEvent.change(emailField, {
target: {
value: '[email protected]'
}
}),
fireEvent.change(usernameField, {
target: {
value: 'user name'
}
}),
fireEvent.change(passwordField, {
target: {
value: 'password123'
}
}),
fireEvent.change(firstNameField, {
await wait(() => {
fireEvent.change(emailField, {
target: {
value: 'user'
value: '[email protected]'
}
}),
fireEvent.change(lastNameField, {
target: {
value: 'name'
}
})
)

await wait(() => {
fireEvent.click(submitButton),
expect(submitSignup).toHaveBeenCalledTimes(1),
expect(submitSignup.mock.calls[0][0]).toEqual({
email: '[email protected]',
username: 'user name',
password: 'password123',
firstName: 'user',
lastName: 'name'
fireEvent.change(usernameField, {
target: {
value: 'user name'
}
}),
fireEvent.change(passwordField, {
target: {
value: 'password123'
}
}),
fireEvent.change(firstNameField, {
target: {
value: 'user'
}
}),
fireEvent.change(lastNameField, {
target: {
value: 'name'
}
})
})
await (async () => {
fireEvent.click(submitButton)
await wait(() => {
expect(submitSignup).toHaveBeenCalledTimes(1),
expect(submitSignup.mock.calls[0][0]).toEqual({
email: '[email protected]',
username: 'user name',
password: 'password123',
firstName: 'user',
lastName: 'name'
})
})
})
})
})
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
"dependencies": {
"@types/yup": "^0.26.30",
"@zeit/next-sass": "^1.0.1",
"apollo-server-micro": "^2.10.1",
"bootstrap": "^4.4.1",
"cookie": "^0.4.0",
"cookies": "^0.8.0",
"formik": "^2.1.4",
"identity-obj-proxy": "^3.0.0",
"isomorphic-unfetch": "3.0.0",
Expand All @@ -35,6 +38,7 @@
"@storybook/addon-viewport": "^5.3.12",
"@storybook/react": "^5.3.12",
"@testing-library/react": "^9.4.0",
"@types/cookie": "^0.3.3",
"@types/node": "^12.12.21",
"@types/react": "^16.9.16",
"@types/react-dom": "^16.9.4",
Expand Down
31 changes: 31 additions & 0 deletions pages/api/graphql.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ApolloServer, gql } from 'apollo-server-micro'

const typeDefs = gql`
type Query {
username: String
hello: String
}
`

const resolvers = {
Query: {
username(_parent: any, _args: any, ctx: any) {
return ctx.user
},
hello() {
return 'hello'
}
}
}

const context = ({ req }: { req: any }) => req.cookies

const apolloServer = new ApolloServer({ typeDefs, resolvers, context })

export const config = {
api: {
bodyParser: false
}
}

export default apolloServer.createHandler({ path: '/api/graphql' })
7 changes: 7 additions & 0 deletions pages/api/hello.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next'

export default (req: NextApiRequest, res: NextApiResponse) => {
const { user } = req.cookies

res.send(`Hello ${user}! From c0d3.com`)
}
16 changes: 16 additions & 0 deletions pages/api/signup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import cookies, { ResWithCookie } from '../../utils/cookies'
import { NextApiRequest } from 'next'

const handler = (req: NextApiRequest, res: ResWithCookie) => {
const { username, email, password, firstName, lastName } = req.body
res.cookie('user', username)
res.json({
username,
email,
password,
firstName,
lastName
})
}

export default cookies(handler)
19 changes: 17 additions & 2 deletions pages/signup.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import { Formik, Form, Field } from 'formik'
import Router from 'next/router'

import Card from '../components/Card'
import Layout from '../components/Layout'
Expand All @@ -15,14 +16,28 @@ const initialValues = {
lastName: ''
}

const Signup: React.FC<Props> = props => (
const Signup: React.FC<Props> = () => (
<Layout>
<Card title="Create Account">
<Formik
validateOnBlur
initialValues={initialValues}
validationSchema={signupValidation}
onSubmit={values => props.submitSignup(values)}
onSubmit={async values => {
const response = await fetch('/api/signup', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(values)
})

const data = await response.json()

if (data) {
Router.push('/api/graphql')
}
}}
>
<Form data-testid="form">
<div className="form-group ">
Expand Down
41 changes: 41 additions & 0 deletions utils/cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { serialize, CookieSerializeOptions } from 'cookie'
import { NextApiResponse, NextApiRequest } from 'next'

export interface ResWithCookie extends NextApiResponse {
cookie: Function
}

/**
* This sets `cookie` on `res` object
*/
const cookie = (
res: NextApiResponse,
name: string,
value: string | object,
options: CookieSerializeOptions = {}
) => {
const stringValue =
typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)

if (options.maxAge) {
options.expires = new Date(Date.now() + options.maxAge)
options.maxAge /= 1000
}

res.setHeader('Set-Cookie', serialize(name, String(stringValue), options))
}

/**
* Adds `cookie` function on `res.cookie` to set cookies for response
*/
const cookies = (handler: Function) => (
req: NextApiRequest,
res: ResWithCookie
) => {
res.cookie = (name: string, value: string, options: CookieSerializeOptions) =>
cookie(res, name, value, options)

return handler(req, res)
}

export default cookies
Loading