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

home work 06 - Promise #23

Open
wants to merge 22 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ node_modules
build
npm-debug.log
.env
.DS_Store
.DS_Store
.idea
35 changes: 24 additions & 11 deletions 04/artur_kudaev/1/func.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
const request = require('request');
const term = require( 'terminal-kit' ).terminal ;

function getData(coords, callback) {

const url = `https://api.darksky.net/forecast/bbb930df7abf0835186e2c34000cfd81/${coords[0]},${coords[1]}`;
function getData(coords) {
return new Promise((resolve, reject) => {
const url = `https://api.darksky.net/forecast/bbb930df7abf0835186e2c34000cfd81/${coords[0]},${coords[1]}`;
request({ url: url, json: true }, (error, response) => {
if(error) {
reject('Opps.. error..')
}else {
resolve(response.body.currently)
}
})
})
};

request({ url: url, json: true }, (error, response) => {
if(error) {
callback('Opps.. error..')
}else {
callback(null, response.body.currently)
}
function getCity() {
return new Promise((resolve, reject) => {
term.magenta( "Enter city: " ) ;
term.inputField(
function( error , input ) {
if(error) reject(error);
resolve(input);
}
) ;
})
}
};

module.exports = {getData}
module.exports = {getData, getCity};
58 changes: 29 additions & 29 deletions 04/artur_kudaev/1/index.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
const func = require('./func');
const chalk = require('chalk');
const term = require( 'terminal-kit' ).terminal ;

const mycoords = [37.8267,-122.4233];

function showData(item, callback) {
func.getData(mycoords, (error, response) => {
if(error) {
console.log(chalk.red(error));
}else {
if(item === 'time') {
console.log(chalk.black.bgWhite.bold(new Date(response[item])));
callback()
}else {
console.log(chalk.black.bgGreen.bold(`${item}: ${response[item]}`));
callback()
}
}
});
}
const cities = require("all-the-cities");

term.cyan( 'Метеоданные Алькатраса.\n' );

var items = [
'summary',
'time',
'temperature',
'ozone',
] ;

term.singleColumnMenu( items , function( error , response ) {
if(response.selectedText) {
showData(`${response.selectedText}`, process.exit)
func.getCity().then(city => {
const data = cities.filter(el => {
return el.name.match(city)
});
const coordinates = data.map(el => el.loc.coordinates);
function showData(item) {
return new Promise((resolve, reject) => {
func.getData(coordinates[0])
.then(response => {
console.log(chalk.black.bgGreen.bold(`${item}: ${response[item]}`));
resolve(true)
})
.catch(err => reject(err))
})
}
} ) ;
func.getData(coordinates[0])
.then(items => {
term.singleColumnMenu( Object.keys(items) , function( error , response ) {
if(error) {
console.log(chalk.black.bgRed.bold(error))
}
else if(response.selectedText) {
showData(`${response.selectedText}`)
.then(() => process.exit())
.catch(err => console.log(err))
}
}) ;
});
})
35 changes: 35 additions & 0 deletions 04/artur_kudaev/1/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions 04/artur_kudaev/1/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "",
"main": "index.js",
"dependencies": {
"all-the-cities": "^3.0.0",
"chalk": "^3.0.0",
"request": "^2.88.0",
"terminal-kit": "^1.32.2"
Expand Down
94 changes: 47 additions & 47 deletions 04/artur_kudaev/2/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,35 @@ const express = require('express');
const path = require('path');
const config = require('./config.js');
const data = require('./data');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const hbs = require("hbs");
const utils = require('./utils');
var bodyParser = require('body-parser')


const app = express();

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use('/hbs', (req, res) => {
res.render('index.hbs')
})

// app.get('/weather', ((req, res) => {
// const cityName = req.query.city;
// if(!cityName) {
// res.sendStatus(400)
// } else {
// utils.getWeatherByString(cityName, (error, weather) => {
// if (error) {
// res.sendStatus(500);
// } else {
// res.status(200).render('weather.hbs', {
// city: weather
// })
// }
// });
// }
//
// }));

app.post('/getweather', urlencodedParser, ((req, res) => {
console.log(req.body);
// if(!cityName) {
// res.sendStatus(400)
// } else {
// utils.getWeatherByString(cityName, (error, weather) => {
// if (error) {
// res.sendStatus(500);
// } else {
// res.status(200).json(weather)
// }
// });
// }

}));


const jsonParser = bodyParser.json();

//Увеличиваю позволенный размер файла
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.set("view engine", "hbs");
hbs.registerPartials(__dirname + "/views/partials");

mongoose.connect("mongodb://localhost:27017/users", { useNewUrlParser: true });

const userScheme = new Schema({
name: String,
age: Number
});
const User = mongoose.model("User", userScheme);

var err = '';

app.use(express.static(path.join(__dirname, '/public')));
app.use(express.static(path.join(__dirname, '/public'), {index: false}));

function error404(req, res, next) {
err = `https://${req.hostname+req.url}`;
Expand All @@ -71,7 +43,34 @@ app.get('/api', (req, res) => {
});

app.get('/', (req, res) => {
res.sendFile('index.html' , { root : __dirname+'/public'});
User.find({}, function (error, response) {
if(error) throw error;
res.render('index.hbs', {
arr: response
})
})
});

app.get('/form', (req, res) => {
res.sendFile('form.html' , { root : __dirname+'/public'});
});

app.post('/save', jsonParser, function(req, res){
if(!req.body) return res.sendStatus(500);
const user = new User({
name: req.body.userName,
age: req.body.age
});
user.save().then(user=>console.log(`Save: ${user}`));
res.sendStatus(200);
});

app.post('/del', jsonParser, function(req, res){
if(!req.body) return res.sendStatus(400);
const id = req.body.id;
User.deleteOne({_id: id}).then(del => console.log(del) );
console.log(id)
res.sendStatus(200)
});

app.use(error404);
Expand All @@ -81,3 +80,4 @@ app.use(function(req, res) {
});

app.listen(config.port, ()=>console.log('Start on port 3000..'));

Loading