Skip to content

Commit

Permalink
add api to unsocial with logic b00tc4mp#177
Browse files Browse the repository at this point in the history
  • Loading branch information
juanpabloarias1 committed Oct 31, 2024
1 parent d641981 commit d246aa8
Show file tree
Hide file tree
Showing 91 changed files with 1,165 additions and 42 deletions.
7 changes: 7 additions & 0 deletions staff/juanp-arias/unsocial/api/data/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import storage from './storage.js'
import uuid from './uuid.js'

export {
storage,
uuid
}
20 changes: 20 additions & 0 deletions staff/juanp-arias/unsocial/api/data/posts.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[
{
"id": "m2xahzukhr",
"image": "https://media.giphy.com/media/3ohhwfAa9rbXaZe86c/giphy.gif?cid=790b7611vkbow49vtlhlh26tztuwge5f7tsvouu717wswm5m&ep=v1_gifs_trending&rid=giphy.gif&ct=g",
"text": "dancing",
"author": "m2x63gb7wns",
"date": "2024-10-31T12:36:34.365Z",
"likes": [],
"comments": []
},
{
"id": "m2xcwohcvqk",
"image": "https://media.giphy.com/media/3ohhwfAa9rbXaZe86c/giphy.gif?cid=790b7611vkbow49vtlhlh26tztuwge5f7tsvouu717wswm5m&ep=v1_gifs_trending&rid=giphy.gif&ct=g",
"text": "dancing",
"author": "m2x63gb7wns",
"date": "2024-10-31T13:43:58.704Z",
"likes": [],
"comments": []
}
]
31 changes: 31 additions & 0 deletions staff/juanp-arias/unsocial/api/data/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import fs from 'fs'

export default {
get users() {
const json = fs.readFileSync('./data/users.json', 'utf-8')

const users = JSON.parse(json)

return users
},

set users(users) {
const json = JSON.stringify(users)

fs.writeFileSync('./data/users.json', json)
},

get posts() {
const json = fs.readFileSync('./data/posts.json', 'utf-8')

const posts = JSON.parse(json)

return posts
},

set posts(posts) {
const json = JSON.stringify(posts)

fs.writeFileSync('./data/posts.json', json)
}
}
11 changes: 11 additions & 0 deletions staff/juanp-arias/unsocial/api/data/storage.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import uuid from './uuid.js'

import storage from './storage.js'

storage.users = [
{ id: uuid(), name: 'Juan Pablo', email: '[email protected]', username: 'juanpablo', password: '123456' }
]

storage.posts = []

console.log(storage.users)
23 changes: 23 additions & 0 deletions staff/juanp-arias/unsocial/api/data/users.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[
{
"id": "m2x3s1fei2j",
"name": "Juan Pablo",
"email": "[email protected]",
"username": "juanpablo",
"password": "123456"
},
{
"id": "m2x63gb7wns",
"name": "Pepito Grillo",
"email": "[email protected]",
"username": "pepitogrillo",
"password": "123456"
},
{
"id": "m2xaj3bwtyn",
"name": "Coco Drilo",
"email": "[email protected]",
"username": "cocodrilo",
"password": "123123123"
}
]
3 changes: 3 additions & 0 deletions staff/juanp-arias/unsocial/api/data/uuid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const uuid = () => (Date.now() + Math.random()).toString(36).replace('.', '')

export default uuid
68 changes: 68 additions & 0 deletions staff/juanp-arias/unsocial/api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import express, { json } from 'express'
import logic from './logic/index.js'

const server = express()

const jsonBodyParser = express.json()

server.use(express.static('public'))

server.post('/authenticate', jsonBodyParser, (req, res) => {
const { username, password } = req.body

try {
const userId = logic.authenticateUser(username, password)

res.json(userId)
} catch (error) {
res.status(401).json({ error: error.constructor.name, message: error.message })

console.error(error)
}
})

server.post('/register', jsonBodyParser, (req, res) => {
const { name, email, username, password, 'password-repeat': passwordRepeat } = req.body

try {
logic.registerUser(name, email, username, password, passwordRepeat)

res.status(201).send()
} catch (error) {
res.status(400).json({ error: error.constructor.name, message: error.message })

console.error(error)
}
})

server.get('/users/:userId/name', (req, res) => {
const { userId } = req.params

try {
const name = logic.getUserName(userId)

res.json(name)
} catch (error) {
res.status(400).json({ error: error.constructor.name, message: error.message })

console.error(error)
}
})

server.post('/posts', jsonBodyParser, (req, res) => {
const userId = req.headers.authorization.slice(6)

const { image, text } = req.body

try {
logic.createPost(userId, image, text)

res.status(201).send()
} catch (error) {
res.status(400).json({ error: error.constructor.name, message: error.message })
}
})



server.listen(7070, () => console.log('api is up'))
16 changes: 16 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/authenticateUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { storage } from '../data/index.js'
import validate from './helpers/validate.js'

export default (username, password) => {
validate.username(username)
validate.password(password)

const { users } = storage

const user = users.find(user => user.username === username && user.password === password)

if (user === undefined)
throw new Error('wrong credentials')

return user.id
}
8 changes: 8 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/authenticateUser.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import authenticateUser from './authenticateUser.js'

try {
console.log(authenticateUser('juanpablo', '123456'))
console.log('logged in')
} catch (error) {
console.error(error)
}
29 changes: 29 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/createPost.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import validate from './helpers/validate.js'

import { storage, uuid } from '../data/index.js'

export default (userId, image, text) => {
validate.id(userId, 'userId')
validate.image(image)
validate.text(text)

const { users, posts } = storage

const found = users.some(({ id }) => id === userId)

if (!found) throw new Error('user not found')

const post = {
id: uuid(),
image: image,
text: text,
author: userId,
date: new Date,
likes: [],
comments: []
}

posts.push(post)

storage.posts = posts
}
7 changes: 7 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/createPost.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import createPost from './createPost.js'

try {
createPost('m2x63gb7wns', 'https://media.giphy.com/media/3ohhwfAa9rbXaZe86c/giphy.gif?cid=790b7611vkbow49vtlhlh26tztuwge5f7tsvouu717wswm5m&ep=v1_gifs_trending&rid=giphy.gif&ct=g', 'dancing')
} catch (error) {
console.error(error)
}
14 changes: 14 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/getUserName.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { storage } from '../data/index.js'
import validate from './helpers/validate.js'

export default userId => {
validate.id(userId, 'userId')

const { users } = storage

const user = users.find(user => user.id === userId)

if (!user) throw new Error('user not found')

return user.name
}
7 changes: 7 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/getUserName.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import getUserName from './getUserName.js'

try {
console.log(getUserName('m2x3s1fei2j'))
} catch (error) {
console.error(error)
}
5 changes: 5 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/helpers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import validate from './validate.js'

export default {
validate
}
54 changes: 54 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/helpers/validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const validateName = name => {
if (typeof name !== 'string') throw new Error('invalid name')
if (name.length < 2)
throw new Error('invalid name length')
}

const validateEmail = email => {
if (typeof email !== 'string') throw new Error('invalid email')
if (!/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(email))
throw new Error('invalid e-mail')
}

const validateUsername = username => {
if (typeof username !== 'string') throw new Error('invalid username')
if (username.length < 4 || username.length > 12)
throw new Error('invalid username length')
}

const validatePassword = password => {
if (typeof password !== 'string') throw new Error('invalid password')
if (password.length < 4)
throw new Error('invalid password length')
}

const validatePasswordsMatch = (password, passwordRepeat) => {
if (typeof passwordRepeat !== 'string') throw new Error('invalid password repeat')
if (password !== passwordRepeat)
throw new Error('passwords do not match')
}

const validateImage = image => {
if (typeof image !== 'string') throw new Error('invalid image')
}

const validateText = text => {
if (typeof text !== 'string') throw new Error('invalid text')
}

const validateId = (id, explain = 'id') => {
if (typeof id !== 'string') throw new Error(`invalid ${explain}`)
}

const validate = {
name: validateName,
email: validateEmail,
username: validateUsername,
password: validatePassword,
passwordsMatch: validatePasswordsMatch,
image: validateImage,
text: validateText,
id: validateId
}

export default validate
14 changes: 14 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import authenticateUser from './authenticateUser.js'
import registerUser from './registerUser.js'
import getUserName from './getUserName.js'
import createPost from './createPost.js'

const logic = {
authenticateUser,
registerUser,
getUserName,

createPost
}

export default logic
24 changes: 24 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/registerUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { storage, uuid } from '../data/index.js'

import validate from './helpers/validate.js'

export default (name, email, username, password, passwordRepeat) => {
validate.name(name)
validate.email(email)
validate.username(username)
validate.password(password)
validate.passwordsMatch(password, passwordRepeat)

const { users } = storage

let user = users.find(user => user.username === username || user.emai === email)

if (user !== undefined)
throw new Error('user already exists')

user = { id: uuid(), name: name, email: email, username: username, password: password }

users.push(user)

storage.users = users
}
7 changes: 7 additions & 0 deletions staff/juanp-arias/unsocial/api/logic/registerUser.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import registerUser from './registerUser.js'

try {
registerUser('Coco Drilo', '[email protected]', 'cocodrilo', '123123123', '123123123')
} catch (error) {
console.error(error)
}
Loading

0 comments on commit d246aa8

Please sign in to comment.