Skip to content
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
109 changes: 106 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,106 @@
node_modules
.idea
/model/test.json

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.idea/
# 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/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# 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 variables file
.env
.env.test

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

# Next.js build output
.next

# 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

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

31 changes: 9 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,18 @@
## GoIT Node.js Course Template Homework
# rest_api_node_js

Выполните форк этого репозитория для выполнения домашних заданий (2-6)
Форк создаст репозиторий на вашем http://github.com
[db connect](https://ibb.co/6v28jyD)

Добавьте ментора в коллаборацию
[get all list](https://ibb.co/9rt82SK)

Для каждой домашней работы создавайте свою ветку.
[Get contact by id](https://ibb.co/s6D8D64)

- hw02
- hw03
- hw04
- hw05
- hw06
[Add new contact](https://ibb.co/y054Zkb)

Каждая новая ветка для дз должна делаться с master
[Update ](https://ibb.co/7QqwG24)

После того как вы закончили выполнять домашнее задание в своей ветке, необходимо сделать пулл-реквест (PR). Потом добавить ментора для ревью кода. Только после того как ментор заапрувит PR, вы можете выполнить мердж ветки с домашним заданием в мастер.
[Update status](https://ibb.co/1zTF2SJ)

Внимательно читайте комментарии ментора. Исправьте замечания и сделайте коммит в ветке с домашним заданием. Изменения подтянуться в PR автоматически после того как вы отправите коммит с исправлениями на github
После исправления снова добавьте ментора на ревью кода.
[Remove contact by id](https://ibb.co/RYncNR2)

- При сдаче домашней работы есть ссылка на PR
- JS-код чистый и понятный, для форматирования используется Prettier
[Remove check](https://ibb.co/c1qt2fp)

### Команды:

- `npm start` — старт сервера в режиме production
- `npm run start:dev` — старт сервера в режиме разработки (development)
- `npm run lint` — запустить выполнение проверки кода с eslint, необходимо выполнять перед каждым PR и исправлять все ошибки линтера
- `npm lint:fix` — та же проверка линтера, но с автоматическими исправлениями простых ошибок
3 changes: 2 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const express = require('express')
const logger = require('morgan')
const cors = require('cors')

const contactsRouter = require('./routes/api/contacts')
const contactsRouter = require('./routes/api/contacts_routers')

const app = express()

Expand All @@ -23,3 +23,4 @@ app.use((err, req, res, next) => {
})

module.exports = app
// 4DQJWQGk6Hyo14Lz
13 changes: 9 additions & 4 deletions bin/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
const app = require('../app')
const db = require('../model/db')
const PORT = process.env.PORT || 3001

const PORT = process.env.PORT || 3000

app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT} !!! :))`)
db.then(() => {
app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT})`)
})
}).catch((error) => {
console.log(`server is not running. Error: ${error.message}`)
process.exit(1)
})
54 changes: 24 additions & 30 deletions routes/api/contacts.js → controllers/contacts_controlers.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
const express = require('express')
const router = express.Router()
const Contacts = require('../model/contacts_model')

const {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
} = require('../../model/index')
const { validCreateContact, validUpdateContact } = require('./validation')

router.get('/', async (req, res, next) => {
const getAll = async (req, res, next) => {
try {
const contacts = await listContacts()
const contacts = await Contacts.getAllContacts()
res.json({
status: 'success',
code: 200,
Expand All @@ -23,12 +13,12 @@ router.get('/', async (req, res, next) => {
} catch (e) {
next(e)
}
})
}

router.get('/:contactId', async (req, res, next) => {
const getByID = async (req, res, next) => {
try {
const contactById = await getContactById(req.params.contactId)
if (contactById) {
const contactById = await Contacts.getContactById(req.params.contactId)
if (contactById.length !== 0) {
return res.json({
status: 'success',
code: 200,
Expand All @@ -46,11 +36,11 @@ router.get('/:contactId', async (req, res, next) => {
} catch (e) {
next(e)
}
})
}

router.post('/', validCreateContact, async (req, res, next) => {
const createContact = async (req, res, next) => {
try {
const contact = await addContact(req.body)
const contact = await Contacts.addContact(req.body)
return res.status(201).json({
status: 'success',
code: 201,
Expand All @@ -61,11 +51,11 @@ router.post('/', validCreateContact, async (req, res, next) => {
} catch (e) {
next(e)
}
})
}

router.delete('/:contactId', async (req, res, next) => {
const deleteContact = async (req, res, next) => {
try {
const contactById = await removeContact(req.params.contactId)
const contactById = await Contacts.removeContact(req.params.contactId)
if (contactById) {
return res.json({
status: 'success',
Expand All @@ -82,11 +72,11 @@ router.delete('/:contactId', async (req, res, next) => {
} catch (e) {
next(e)
}
})
}

router.patch('/:contactId', validUpdateContact, async (req, res, next) => {
const updateContact = async (req, res, next) => {
try {
const contactById = await updateContact(req.params.contactId, req.body)
const contactById = await Contacts.updateContact(req.params.contactId, req.body)
if (contactById) {
return res.json({
status: 'success',
Expand All @@ -103,7 +93,11 @@ router.patch('/:contactId', validUpdateContact, async (req, res, next) => {
} catch (e) {
next(e)
}
})

// res.json({ message: 'template message' })
module.exports = router
}
module.exports = {
createContact,
getAll,
getByID,
updateContact,
deleteContact,
}
74 changes: 0 additions & 74 deletions model/contacts.json

This file was deleted.

37 changes: 37 additions & 0 deletions model/contacts_model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const Contacts = require('./schemas/contacts_schemas')

const addContact = async (body) => {
const result = await Contacts.create(body)
return result
}
const getAllContacts = async () => {
const res = await Contacts.find({})
return res
}

const getContactById = async (contactId) => {
const res = await Contacts.find({ _id: contactId })
return res
}

const updateContact = async (contactId, body) => {
const res = await Contacts.findOneAndUpdate(
{ _id: contactId },
{ ...body },
{ new: true }
)
return res
}

const removeContact = async (contactId) => {
const res = await Contacts.findOneAndDelete({ _id: contactId },)
return res
}

module.exports = {
addContact,
getAllContacts,
getContactById,
updateContact,
removeContact,
}
Loading