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

Hw02 expressV2 #5504

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
130 changes: 128 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.idea
.vscode
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
4 changes: 4 additions & 0 deletions .gitignore copy
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
.env
.idea
.vscode
18 changes: 8 additions & 10 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')

const contactsRouter = require('./routes/api/contacts')
import express from 'express';
import logger from 'morgan';
import cors from 'cors';
import router from './routes/api/contacts.js'

const app = express()

const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short'

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())

app.use('/api/contacts', contactsRouter)
app.use('/api/contacts', router)

app.use((req, res) => {
res.status(404).json({ message: 'Not found' })
})

app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
const { status = 500, message = 'Server error' } = err;
res.status(status).json({ message })
})

module.exports = app
export default app;
82 changes: 82 additions & 0 deletions controllers/contacts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import Joi from 'joi';
import { listContacts, getContactById, updateContact, removeContact, addContact } from "../models/contacts.js"
import { HttpError } from '../helpers/HttpErrors.js';

const addSchema = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
phone: Joi.string().required()
});

const putSchema = Joi.object({
name: Joi.string(),
email: Joi.string().email(),
phone: Joi.string()
}).or("name", "email", "phone");

export const getAll = async (req, res, next) => {
try {
const result = await listContacts();
res.status(200).json(result)
} catch (error) {
next(error);
}
};

export const getById = async (req, res, next) => {
try {
const { contactId } = req.params
const result = await getContactById(contactId);
if (!result) {
throw HttpError(404, "Not found")
}
res.status(200).json(result)
} catch (error) {
next(error);
}
};

export const postContact = async (req, res, next) => {
try {
const { error } = addSchema.validate(req.body)
if (error) {
throw HttpError(400, error.message)
}
const result = await addContact(req.body);
res.status(201).json(result)
} catch (error) {
next(error);
}
};

export const deleteContact = async (req, res, next) => {
try {
const { contactId } = req.params
const result = await removeContact(contactId);
if (!result) {
throw HttpError(404, "Not found")
}
res.status(200).json({
message: 'Contact deleted'
})
} catch (error) {
next(error);
}
};

export const putContact = async (req, res, next) => {
try {
const { error } = putSchema.validate(req.body)
if (error) {
throw HttpError(400, error.message)
}
const { contactId } = req.params;
const result = await updateContact(contactId, req.body);
if (!result) {
throw HttpError(404, "Not found")
}
res.status(200).json(result)
} catch (error) {
next(error);
}
};
5 changes: 5 additions & 0 deletions helpers/HttpErrors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const HttpError = (status, message) => {
const error = new Error(message);
error.status = status;
return error;
};
62 changes: 49 additions & 13 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,55 @@
// const fs = require('fs/promises')
import fs from "fs/promises";
import path from "path";
import { nanoid } from 'nanoid';

const listContacts = async () => {}
const contactsPath = path.resolve('models', 'contacts.json');

const getContactById = async (contactId) => {}
export const listContacts = async () => {
const date = await fs.readFile(contactsPath);
return JSON.parse(date);
};

const removeContact = async (contactId) => {}
export const getContactById = async (contactId) => {
const contacts = await listContacts();
const contactById = contacts.find(({ id }) =>
id === contactId
)
return contactById || null;
};

const addContact = async (body) => {}
export const removeContact = async (contactId) => {
const contacts = await listContacts();
const removeIndex = contacts.findIndex(({ id }) =>
id === contactId
);
if (removeIndex === -1) {
return null;
};
const removeContact = contacts.splice(removeIndex, 1);
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2))
return removeContact;
};

const updateContact = async (contactId, body) => {}
export const addContact = async ({name, email, phone}) => {
const newContact = { id: nanoid(), name, email, phone };
const contacts = await listContacts();
contacts.push(newContact);
await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return newContact;
};

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
}

export const updateContact = async (contactId, body) => {
const contacts = await listContacts();
const index = contacts.findIndex(({ id }) =>
id === contactId
);
if (index === -1) {
return null;
};

contacts[index] = { ...contacts[index], ...body };

await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2));
return contacts[index];
};
Loading