Skip to content

Commit

Permalink
[Web] TypeScript
Browse files Browse the repository at this point in the history
  • Loading branch information
JuanM04 committed Oct 12, 2019
1 parent 2ed3205 commit 1b45dce
Show file tree
Hide file tree
Showing 27 changed files with 188 additions and 119 deletions.
12 changes: 12 additions & 0 deletions web/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// <reference types="next" />
/// <reference types="next/types/global" />

type BaseUser = {
dni: number
viajes: number
}

type BasePrices = {
viajePrice: number
pasePrice: number
}
21 changes: 10 additions & 11 deletions web/next.config.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
const path = require('path')
const withSass = require('@zeit/next-sass')
const withOffline = require('next-offline')

const isDev = process.env.NODE_ENV !== 'production'
const path = dir => require('path').resolve(__dirname, dir)

module.exports = withSass(
withOffline({
webpack: config => {
// Aliases that let you do "import component from 'components'" instead of "import component from '../components'"
config.resolve.alias['pages'] = path.join(__dirname, 'src/pages')
config.resolve.alias['components'] = path.join(
__dirname,
'src/components'
)
config.resolve.alias['utils'] = path.join(__dirname, 'src/utils')
config.resolve.alias['prisma'] = path.join(
__dirname,
'prisma/generated/prisma-client'
)
config.resolve.alias = {
...config.resolve.alias,
pages: path('src/pages'),
components: path('src/components/index.ts'),
utils: path('src/utils'),
prisma: path('prisma/generated/prisma-client/index.ts'),
}

config.resolve.extensions.push('.ts', '.tsx')
return config
},

Expand Down
5 changes: 4 additions & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
"slugify": "^1.3.5"
},
"devDependencies": {
"dotenv": "^8.1.0"
"@types/micro": "^7.3.3",
"@types/react": "^16.9.5",
"dotenv": "^8.1.0",
"typescript": "^3.6.4"
}
}
30 changes: 0 additions & 30 deletions web/prisma/generated/prisma-client/index.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -993,4 +993,10 @@ export const models: Model[] = [
* Type Defs
*/

export const prisma: Prisma;
export const Prisma = makePrismaClientClass<ClientConstructor<Prisma>>({
typeDefs,
models,
endpoint: `${process.env["PRISMA_ENDPOINT"]}`,
secret: `${process.env["PRISMA_SECRET"]}`
});
export const prisma = new Prisma();
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
module.exports = {
typeDefs: // Code generated by Prisma ([email protected]). DO NOT EDIT.
// Code generated by Prisma ([email protected]). DO NOT EDIT.
// Please don't change this file manually but run `prisma generate` to update it.
// For more information, please read the docs: https://www.prisma.io/docs/prisma-client/

/* GraphQL */ `type AggregateLog {
export const typeDefs = /* GraphQL */ `type AggregateLog {
count: Int!
}
Expand Down Expand Up @@ -474,6 +473,4 @@ input UserWhereUniqueInput {
uid: String
dni: Int
}
`
}

`
2 changes: 1 addition & 1 deletion web/prisma/prisma.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ datamodel: datamodel.prisma
secret: ${env:PRISMA_SECRET}

generate:
- generator: javascript-client
- generator: typescript-client
output: ./generated/prisma-client/
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import React, { useState } from 'react'
import slugify from 'slugify'
import { Button, FormInput, InputGroup, InputGroupAddon } from 'shards-react'

export default ({ loading, callback }) => {
interface Props {
loading: boolean
callback(dni: string): void
}

export default (props: Props) => {
const { loading, callback } = props
const [dniInput, setDniInput] = useState('')

return (
Expand All @@ -11,9 +17,7 @@ export default ({ loading, callback }) => {
placeholder="DNI"
value={dniInput}
onChange={e =>
setDniInput(
parseInt(slugify(e.target.value, { remove: /[^\d]+/g })) || ''
)
setDniInput(slugify(e.target.value, { remove: /[^\d]+/g }) || '')
}
onKeyPress={e => {
if (loading || dniInput === '') return
Expand Down
6 changes: 5 additions & 1 deletion web/src/components/FAQ.js → web/src/components/FAQ.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import {

import FAQ from 'utils/faq.json'

export default ({ pasePrice }) => (
interface Props {
pasePrice: number | string
}

export default ({ pasePrice }: Props) => (
<Card className="FAQ">
<h3>Preguntas Frecuentes</h3>
<ListGroup flush>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import React from 'react'
import { Button, Card, CardBody, Col, Row } from 'shards-react'

export default ({ user: { viajes, dni }, viajePrice, logOut }) => (
interface Props {
user: BaseUser
viajePrice: number | string
logOut(): void
}

export default ({ user, viajePrice, logOut }: Props) => (
<Card className="Board">
<CardBody>
<Row className="top">
<Col>
<span className="big">{viajes}</span>
<span className="big">{user.viajes}</span>
<span className="small">viajes</span>
</Col>
<Col>
Expand All @@ -17,7 +23,7 @@ export default ({ user: { viajes, dni }, viajePrice, logOut }) => (
<hr />
<Row className="bottom">
<Col>
<span>DNI: {dni.toLocaleString('es')}</span>
<span>DNI: {user.dni.toLocaleString('es')}</span>
</Col>
<Col xs="4">
<Button theme="primary" pill outline size="sm" onClick={logOut}>
Expand Down
File renamed without changes.
File renamed without changes.
22 changes: 0 additions & 22 deletions web/src/pages/api/checker.js

This file was deleted.

22 changes: 22 additions & 0 deletions web/src/pages/api/checker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { text } from 'micro'
import { prisma } from 'prisma'
import { IncomingMessage, OutgoingMessage } from 'http'

export default async (req: IncomingMessage, res: OutgoingMessage) => {
try {
if (req.headers.secret !== process.env.SECRET) throw 'error!'
const uid = await text(req)

let user = await prisma.user({ uid })
if (!user) throw 'error!'

const metadata = await prisma.metadatas({
orderBy: 'date_ASC',
last: 1,
})

res.end(`res:${user.viajes}-${metadata[0].viajePrice}!`)
} catch (error) {
res.end(error)
}
}
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ApolloError, AuthenticationError } from 'apollo-server-micro'
import { prisma } from 'prisma'

const checkAuth = authed => {
const checkAuth = (authed: boolean) => {
if (!authed) throw new AuthenticationError('Inavlid Secret')
}

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const { text } = require('micro')
const { prisma } = require('prisma')

module.exports = async (req, res) => {
if (req.headers.secret !== process.env.SECRET) throw 'error!'
const uid = await text(req)
import { text } from 'micro'
import { prisma } from 'prisma'
import { IncomingMessage, OutgoingMessage } from 'http'

export default async (req: IncomingMessage, res: OutgoingMessage) => {
try {
if (req.headers.secret !== process.env.SECRET) throw 'error!'
const uid = await text(req)

let user = await prisma.user({ uid })
if (!user) throw 'error!'
if (!user.viajes) throw 'viajes:-1!'
Expand All @@ -22,8 +23,8 @@ module.exports = async (req, res) => {
data: { initialViajes: user.viajes + 1 },
})

res.send(`viajes:${user.viajes}!`)
res.end(`viajes:${user.viajes}!`)
} catch (error) {
res.send(error)
res.end(error)
}
}
56 changes: 33 additions & 23 deletions web/src/pages/index.js → web/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,33 @@ import apolloClient, { GET_VIAJES, GET_PRICES } from 'utils/apollo'
import { DniInput, FAQ, ViajesCard } from 'components'
import { Alert, Container } from 'shards-react'

function App(props) {
type User = false | BaseUser
type Prices = false | BasePrices

interface Props {
prices: Prices
user: User
}

function App(props: Props) {
const [online, setOnline] = useState(true)
const [prices, setPrices] = useState(props.prices)
const [user, setUser] = useState(props.user)
const [loading, setLoading] = useState(false)

const getUser = dni => {
dni = parseInt(dni)
const getUser = (dni: string) => {
setLoading(true)

apolloClient
.query({
query: GET_VIAJES,
variables: { dni },
variables: { dni: parseInt(dni) },
})
.then(({ data }) => {
.then(res => {
const user: User = res.data.user
setLoading(false)
if (!data.user) alert('El usuario no existe')
else setUser(data.user)
if (!user) alert('El usuario no existe')
else setUser(user)
})
.catch(console.error)
}
Expand Down Expand Up @@ -53,7 +61,7 @@ function App(props) {
if (typeof window === 'undefined') return
storage.set('query-user', user)

if (!user.dni) return
if (!user) return
nookies.set({}, 'user', user.dni.toString(), {
maxAge: 30 * 24 * 60 * 60, // 30 days
path: '/',
Expand All @@ -73,47 +81,49 @@ function App(props) {
</Alert>
)}

{!user.dni && online && <DniInput loading={loading} callback={getUser} />}
{!user && online && <DniInput loading={loading} callback={getUser} />}

{user.dni && (
{user && (
<ViajesCard
viajePrice={prices.viajePrice || '--'}
viajePrice={prices ? prices.viajePrice : '--'}
user={user}
logOut={() => {
setUser({})
setUser(false)
nookies.destroy({}, 'user')
}}
/>
)}

<FAQ pasePrice={prices.pasePrice || '--'} />
<FAQ pasePrice={prices ? prices.pasePrice : '--'} />
</Container>
)
}

App.getInitialProps = async ctx => {
try {
const prices = await apolloClient.query({ query: GET_PRICES })
let user: User = false,
prices: Prices = false

const pricesRes = await apolloClient.query({ query: GET_PRICES })
if ('data' in pricesRes) prices = pricesRes.data.metadata

// "If there's a user in the cookies, get it"
let user = {}
const { user: dni } = nookies.get(ctx)
if (dni)
user = await apolloClient.query({
if (dni) {
const userRes = await apolloClient.query({
query: GET_VIAJES,
variables: { dni: parseInt(dni) },
})

return {
prices: prices.data ? prices.data.metadata : {},
user: user.data ? user.data.user : {},
if ('data' in userRes) user = userRes.data.user
}

return { prices, user }
} catch (error) {
console.error(error)
nookies.destroy(ctx, 'user')
return {
prices: {},
user: {},
prices: false,
user: false,
}
}
}
Expand Down
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 1b45dce

Please sign in to comment.