SlideShare a Scribd company logo
www.luxoft.com
Fantastic Template Stings
Yuriy Voziy
and Where to Use Them
www.luxoft.com
Привіт
www.luxoft.com
ES5 Style
const name = 'Yuriy Voziy';
const city = 'Kyiv';
const birth = 1984;
const greeting = '<html>' + "n"
+ '<body>' + "n"
+ '<div>' + "n"
+ 'Hi, my name is ' + name + ".n"
+ 'I live in ' + _.upperFirst(city) + ".n"
+ _.upperFirst(city) + " is a beatiful place!n"
+ "</div></body></html>";
www.luxoft.com
With ES6 Template Strings
const name = 'Yuriy Voziy';
const city = 'Kyiv';
const birth = 1984;
const greeting = `<html>
<body>
<div>
Hi, my name is ${name}.
I am ${new Date().getFullYear() - birth} years old.
I live in ${_.upperFirst(city)}.
And I must say that ${_.upperFirst(city)} is a beautiful place!
</div>
</body>
</html>`
www.luxoft.com
Let’s write a simple log function
function log(strings) {
console.log(string[0]);
}
log `Entering log data`
// Prints "Entering log data"
www.luxoft.com
Let’s make it look nice
const log = ([strings]) => console.log(string);
log `Entering log data`
// Prints "Entering log data"
That’s better
www.luxoft.com
What about variables?
const log = ([string]) => console.log(string);
log `Entering log data`
// Prints "Entering log data“
log `Entered variable: ${1}`
// Prints "Entered variable: "
//Fix
const log = ([string], data) => console.log(string, data);
log `Entered variable: ${1}`
// Prints "Entered variable: 1"
Що трапилось?
Всі змінні передаються у шаблонну
функцію, як аргументи.
Зазвичай нам потрібно зробити
щось більше, ніж надрукувати всі
строки разом.
www.luxoft.com
Let’s make it universal
const log = (strings, ...values) =>
console.log(strings.reduce(
(str, value, index) => str += value + (values[index] || '')
, ''))
log `Welcome to ${new Date().getFullYear()}
Your local date is: ${new Date}`
//Welcome to 2018
//Your local date is: Mon Dec 03 2018 20:45:59 GMT+0200 (Eastern European Standard Time)
www.luxoft.com
Use it as i18n
// default
i18n `Hello ${'World'}`
// "Hello World"
// we switch to German
i18n.locale = 'de';
// but we still write in English
i18n`Hello ${'World'}`
// "Hallo World"
i18n.locale = 'it';
i18n `Hello ${'World'}`
// Ciao World
i18n.locale = 'sp';
i18n `Hello ${'World'}`
// Hola World
https://codeburst.io/easy-i18n-in-10-lines-of-javascript-poc-eb9e5444d71e
www.luxoft.com
Use it for a SQL queries
const SQL = require('sql-template-strings')
const book = 'harry potter'
const author = 'J. K. Rowling'
// sequelize:
sequelize.query('SELECT author FROM books WHERE name = ? AND author = ?', {replacements: [book, author]})
// is equivalent to
sequelize.query(SQL `SELECT author FROM books WHERE name = ${book} AND author = ${author}`)
https://github.com/felixfbecker/node-sql-template-strings
www.luxoft.com
Or slightly modify to be more advanced
//If we slightly modify this
const SQL = require('sql-query')
const Sequelize = require('sequelize')
SQL.db = new Sequelize('mysql://user:pass@example.com:9821/db_name')
const results = await SQL `SELECT author FROM books WHERE name = ${book} AND author = ${author}` ()
https://github.com/felixfbecker/node-sql-template-strings
www.luxoft.com
Create a shorthand for your configs
function _get([key], object) {
if (object) {
return _.get(object, key);
}
return (object, defValue) => _.get(object, key, defValue);
}
let config = {
author: 'Yuriy Voziy',
company: {
name: 'Luxoft',
url: 'https://career.luxoft.com',
office: {
rad: {
name: 'Irva',
address: 'Rad 1014'
}
}
}
}
_get `company.office.rad.name` (config, 'Dafault') //Irva
_get `company.of_fice.rad.name` (config) || 'Default' //Default
_get `company.office.rad.name${config}`; // Irva
www.luxoft.com
Use a shorthand for your nested JSONs
function _get([key], object) {
if (object) {
return _.get(object, key);
}
return (object, defValue) => _.get(object, key, defValue);
}
let config = {
author: 'Yuriy Voziy',
company: {
name: 'Luxoft',
url: 'https://career.luxoft.com',
office: {
rad: {
name: 'Irva',
address: 'Rad 1014'
}
}
}
}
_get `company.office.rad.name` (config, 'Dafault') //Irva
_get `company.of_fice.rad.name` (config) || 'Default' //Default
_get `company.office.rad.name${config}`; // Irva
www.luxoft.com
Or create a wrapper for the configs
let config = {
author: 'Yuriy Voziy',
company: {
name: 'Luxoft',
url: 'https://career.luxoft.com'
}
}
_get.wrap = function (object) {
return ([key], keyv) => _.get(object, key || keyv);
}
_config = _get.wrap(config);
log `${ _config `company.name` }` //Luxoft
log `${ _config `company.url` }` //https://career.Luxoft.com
www.luxoft.com
Fetching urls
_fetch = ([url], urlv) => fetch(url || urlv);
//This is just to make
_fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0`
//and
_fetch `${_config `site.url`}`
//and
fetch (_config `site.url`)
//Work the same
www.luxoft.com
But it returns Promise inside a Promise
//But this returns promise inside promise ☹
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Response
body: ReadableStream
locked: false
__proto__: Object
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://www.mocky.io/v2/5c058daf3300005f01e812e0"
__proto__: Response
www.luxoft.com
So let’s make comfort of this
//Most of the times we want data, so let's wait for it
_fetch = ([url], ...[urlv]) => new Promise((resolve, reject) =>
fetch(url || urlv).then((response) => resolve(response.json())).catch(reject)
);
await _fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0` //{hello: {my: 'world’}}
await _fetch `${ _config `site.url` }` //{hello: {my: 'world'}}
//Still no HEAD, POST, PUT, DELETE and other header though…
www.luxoft.com
And add some comfort and possibilities
_fetch = ([url, urlb], ...[urlv, options]) => new Promise((resolve, reject) =>
fetch(url || urlb || urlv, typeof urlv == 'string' ? options : urlv)
.then((response) => resolve(response.json()))
.catch(reject));
_fetch.options = ([url], ...[urlv]) => ([], ...[options]) =>
_fetch `${url || urlv}${options}`;
const options = {method: 'post'}
const resp = _fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0`
.then(console.log)
.catch(console.error)
const resp = await _fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0 ${options}`
const resp = await _fetch `${options} http://www.mocky.io/v2/5c058daf3300005f01e812e0`
const resp = await _fetch.options(options) `http://www.mocky.io/v2/5c058daf3300005f01e812e0`
log `${ _get `my.deep.value` `${await _fetch(options) `http://www.mocky.io/v2/5c058daf3300005f01e812e0`}`}`
log `${ _get `my.deep.value` (resp)}`
www.luxoft.com
Dependency injection
require = require('req')
const {log, i18n, _get, _fetch} = require `utils`
const Sequelize = require `sequelize`
const {dependency, inject, dependencies} = require `di`
const lodash = require `lodash`
const _config = _get.wrap(require `config`)
dependency `db` (new Sequelize( _config `db.string `))
dependency `sql` (require `sql-query`)
dependency `log ${log}`
dependency `fetch` (require `node-fetch`)
dependency `_ ${lodash}`
const {log, SQL, _fetch} = dependencies('log', 'sql', '_fetch')
const resp = await _fetch `${ _config `site.url` } ${ _config `site.options` }`
SQL `INSERT INTO myvalues (${ _get `my.deep.value` (resp) }, ${ _get `hello` (resp)} )` ()
.then( (v) => inject `log` `${ i18n `Successfully inserted record: ${v}` }`)
.catch(console.error.bind(null, i18n `Error inserting value: `, v))
www.luxoft.com
Дякую
yvoziy@luxoft.com

More Related Content

What's hot

Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
Remy Sharp
 
Alexander Mostovenko "Modern approach to localization in javascript with the ...
Alexander Mostovenko "Modern approach to localization in javascript with the ...Alexander Mostovenko "Modern approach to localization in javascript with the ...
Alexander Mostovenko "Modern approach to localization in javascript with the ...
OdessaJS Conf
 
I put on my mink and wizard behat (tutorial)
I put on my mink and wizard behat (tutorial)I put on my mink and wizard behat (tutorial)
I put on my mink and wizard behat (tutorial)
xsist10
 
I put on my mink and wizard behat (talk)
I put on my mink and wizard behat (talk)I put on my mink and wizard behat (talk)
I put on my mink and wizard behat (talk)
xsist10
 
How to learn j query
How to learn j queryHow to learn j query
How to learn j queryBaoyu Xu
 
How to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrainHow to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrain
Codemotion Tel Aviv
 
IsTrue(true)?
IsTrue(true)?IsTrue(true)?
IsTrue(true)?
David Golden
 
Testing Web Applications with GEB
Testing Web Applications with GEBTesting Web Applications with GEB
Testing Web Applications with GEB
Howard Lewis Ship
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
Wim Godden
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjC
Lin Luxiang
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
husnara mohammad
 
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Puppet
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Intro to OAuth
Intro to OAuthIntro to OAuth
Intro to OAuth
mfrost503
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
musrath mohammad
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)
Joel Lord
 

What's hot (20)

Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
CGI.pm - 3ло?!
CGI.pm - 3ло?!CGI.pm - 3ло?!
CGI.pm - 3ло?!
 
Alexander Mostovenko "Modern approach to localization in javascript with the ...
Alexander Mostovenko "Modern approach to localization in javascript with the ...Alexander Mostovenko "Modern approach to localization in javascript with the ...
Alexander Mostovenko "Modern approach to localization in javascript with the ...
 
I put on my mink and wizard behat (tutorial)
I put on my mink and wizard behat (tutorial)I put on my mink and wizard behat (tutorial)
I put on my mink and wizard behat (tutorial)
 
I put on my mink and wizard behat (talk)
I put on my mink and wizard behat (talk)I put on my mink and wizard behat (talk)
I put on my mink and wizard behat (talk)
 
How to learn j query
How to learn j queryHow to learn j query
How to learn j query
 
How to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrainHow to actually use promises - Jakob Mattsson, FishBrain
How to actually use promises - Jakob Mattsson, FishBrain
 
IsTrue(true)?
IsTrue(true)?IsTrue(true)?
IsTrue(true)?
 
Session8
Session8Session8
Session8
 
Testing Web Applications with GEB
Testing Web Applications with GEBTesting Web Applications with GEB
Testing Web Applications with GEB
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Add loop shortcode
Add loop shortcodeAdd loop shortcode
Add loop shortcode
 
Javascript call ObjC
Javascript call ObjCJavascript call ObjC
Javascript call ObjC
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Intro to OAuth
Intro to OAuthIntro to OAuth
Intro to OAuth
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)
 

Similar to Yuriy Voziy "Fantastic Template Strings and Where to Use Them"

Ruby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersRuby on Rails: Tasty Burgers
Ruby on Rails: Tasty Burgers
Aaron Patterson
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
Kacper Gunia
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
Wynn Netherland
 
JavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New WorldJavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New World
Robert Nyman
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
Anatoly Sharifulin
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning C
David Wheeler
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
jaespinmora
 
Symfony without the framework
Symfony without the frameworkSymfony without the framework
Symfony without the framework
GOG.com dev team
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
Workhorse Computing
 
HTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC EditionHTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC Edition
Xavier Mertens
 
Chloe and the Realtime Web
Chloe and the Realtime WebChloe and the Realtime Web
Chloe and the Realtime Web
Trotter Cashion
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
Marcus Ramberg
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Dotan Dimet
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Kacper Gunia
 
Micropage in microtime using microframework
Micropage in microtime using microframeworkMicropage in microtime using microframework
Micropage in microtime using microframework
Radek Benkel
 
Beyond the Final Frontier of jQuery Selectors
Beyond the Final Frontier of jQuery SelectorsBeyond the Final Frontier of jQuery Selectors
Beyond the Final Frontier of jQuery Selectors
Alexander Shopov
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 

Similar to Yuriy Voziy "Fantastic Template Strings and Where to Use Them" (20)

Ruby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersRuby on Rails: Tasty Burgers
Ruby on Rails: Tasty Burgers
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
 
JavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New WorldJavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New World
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning C
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
 
Symfony without the framework
Symfony without the frameworkSymfony without the framework
Symfony without the framework
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
 
HTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC EditionHTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC Edition
 
Chloe and the Realtime Web
Chloe and the Realtime WebChloe and the Realtime Web
Chloe and the Realtime Web
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
 
ApacheCon 2005
ApacheCon 2005ApacheCon 2005
ApacheCon 2005
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Micropage in microtime using microframework
Micropage in microtime using microframeworkMicropage in microtime using microframework
Micropage in microtime using microframework
 
Beyond the Final Frontier of jQuery Selectors
Beyond the Final Frontier of jQuery SelectorsBeyond the Final Frontier of jQuery Selectors
Beyond the Final Frontier of jQuery Selectors
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 

More from LogeekNightUkraine

Face recognition with c++
Face recognition with c++ Face recognition with c++
Face recognition with c++
LogeekNightUkraine
 
C++20 features
C++20 features C++20 features
C++20 features
LogeekNightUkraine
 
Autonomous driving on your developer pc. technologies, approaches, future
Autonomous driving on your developer pc. technologies, approaches, futureAutonomous driving on your developer pc. technologies, approaches, future
Autonomous driving on your developer pc. technologies, approaches, future
LogeekNightUkraine
 
Orkhan Gasimov "High Performance System Design"
Orkhan Gasimov "High Performance System Design" Orkhan Gasimov "High Performance System Design"
Orkhan Gasimov "High Performance System Design"
LogeekNightUkraine
 
Vitalii Korzh "Managed Workflows or How to Master Data"
Vitalii Korzh "Managed Workflows or How to Master Data" Vitalii Korzh "Managed Workflows or How to Master Data"
Vitalii Korzh "Managed Workflows or How to Master Data"
LogeekNightUkraine
 
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
LogeekNightUkraine
 
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
Oleksii Kuchuk "Reading gauge values with open cv imgproc"Oleksii Kuchuk "Reading gauge values with open cv imgproc"
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
LogeekNightUkraine
 
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
LogeekNightUkraine
 
Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"
LogeekNightUkraine
 
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
LogeekNightUkraine
 
Iurii Antykhovych "Java and performance tools and toys"
Iurii Antykhovych "Java and performance tools and toys"Iurii Antykhovych "Java and performance tools and toys"
Iurii Antykhovych "Java and performance tools and toys"
LogeekNightUkraine
 
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
LogeekNightUkraine
 
Aleksandr Kutsan "Managing Dependencies in C++"
Aleksandr Kutsan "Managing Dependencies in C++"Aleksandr Kutsan "Managing Dependencies in C++"
Aleksandr Kutsan "Managing Dependencies in C++"
LogeekNightUkraine
 
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
LogeekNightUkraine
 
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
Alexandr Golyak, Nikolay Chertkov  "Automotive Testing vs Test Automatio"Alexandr Golyak, Nikolay Chertkov  "Automotive Testing vs Test Automatio"
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
LogeekNightUkraine
 
Michal Kordas "Docker: Good, Bad or Both"
Michal Kordas "Docker: Good, Bad or Both"Michal Kordas "Docker: Good, Bad or Both"
Michal Kordas "Docker: Good, Bad or Both"
LogeekNightUkraine
 
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
LogeekNightUkraine
 
Shestakov Illia "The Sandbox Theory"
Shestakov Illia "The Sandbox Theory"Shestakov Illia "The Sandbox Theory"
Shestakov Illia "The Sandbox Theory"
LogeekNightUkraine
 
Dmytro Kochergin “Autotest with CYPRESS”
Dmytro Kochergin “Autotest with CYPRESS”Dmytro Kochergin “Autotest with CYPRESS”
Dmytro Kochergin “Autotest with CYPRESS”
LogeekNightUkraine
 
Ivan Dryzhyruk “Ducks Don’t Like Bugs”
Ivan Dryzhyruk “Ducks Don’t Like Bugs”Ivan Dryzhyruk “Ducks Don’t Like Bugs”
Ivan Dryzhyruk “Ducks Don’t Like Bugs”
LogeekNightUkraine
 

More from LogeekNightUkraine (20)

Face recognition with c++
Face recognition with c++ Face recognition with c++
Face recognition with c++
 
C++20 features
C++20 features C++20 features
C++20 features
 
Autonomous driving on your developer pc. technologies, approaches, future
Autonomous driving on your developer pc. technologies, approaches, futureAutonomous driving on your developer pc. technologies, approaches, future
Autonomous driving on your developer pc. technologies, approaches, future
 
Orkhan Gasimov "High Performance System Design"
Orkhan Gasimov "High Performance System Design" Orkhan Gasimov "High Performance System Design"
Orkhan Gasimov "High Performance System Design"
 
Vitalii Korzh "Managed Workflows or How to Master Data"
Vitalii Korzh "Managed Workflows or How to Master Data" Vitalii Korzh "Managed Workflows or How to Master Data"
Vitalii Korzh "Managed Workflows or How to Master Data"
 
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
 
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
Oleksii Kuchuk "Reading gauge values with open cv imgproc"Oleksii Kuchuk "Reading gauge values with open cv imgproc"
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
 
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
 
Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"
 
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
 
Iurii Antykhovych "Java and performance tools and toys"
Iurii Antykhovych "Java and performance tools and toys"Iurii Antykhovych "Java and performance tools and toys"
Iurii Antykhovych "Java and performance tools and toys"
 
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
 
Aleksandr Kutsan "Managing Dependencies in C++"
Aleksandr Kutsan "Managing Dependencies in C++"Aleksandr Kutsan "Managing Dependencies in C++"
Aleksandr Kutsan "Managing Dependencies in C++"
 
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
 
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
Alexandr Golyak, Nikolay Chertkov  "Automotive Testing vs Test Automatio"Alexandr Golyak, Nikolay Chertkov  "Automotive Testing vs Test Automatio"
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
 
Michal Kordas "Docker: Good, Bad or Both"
Michal Kordas "Docker: Good, Bad or Both"Michal Kordas "Docker: Good, Bad or Both"
Michal Kordas "Docker: Good, Bad or Both"
 
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
 
Shestakov Illia "The Sandbox Theory"
Shestakov Illia "The Sandbox Theory"Shestakov Illia "The Sandbox Theory"
Shestakov Illia "The Sandbox Theory"
 
Dmytro Kochergin “Autotest with CYPRESS”
Dmytro Kochergin “Autotest with CYPRESS”Dmytro Kochergin “Autotest with CYPRESS”
Dmytro Kochergin “Autotest with CYPRESS”
 
Ivan Dryzhyruk “Ducks Don’t Like Bugs”
Ivan Dryzhyruk “Ducks Don’t Like Bugs”Ivan Dryzhyruk “Ducks Don’t Like Bugs”
Ivan Dryzhyruk “Ducks Don’t Like Bugs”
 

Recently uploaded

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 

Recently uploaded (20)

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 

Yuriy Voziy "Fantastic Template Strings and Where to Use Them"

  • 3. www.luxoft.com ES5 Style const name = 'Yuriy Voziy'; const city = 'Kyiv'; const birth = 1984; const greeting = '<html>' + "n" + '<body>' + "n" + '<div>' + "n" + 'Hi, my name is ' + name + ".n" + 'I live in ' + _.upperFirst(city) + ".n" + _.upperFirst(city) + " is a beatiful place!n" + "</div></body></html>";
  • 4. www.luxoft.com With ES6 Template Strings const name = 'Yuriy Voziy'; const city = 'Kyiv'; const birth = 1984; const greeting = `<html> <body> <div> Hi, my name is ${name}. I am ${new Date().getFullYear() - birth} years old. I live in ${_.upperFirst(city)}. And I must say that ${_.upperFirst(city)} is a beautiful place! </div> </body> </html>`
  • 5. www.luxoft.com Let’s write a simple log function function log(strings) { console.log(string[0]); } log `Entering log data` // Prints "Entering log data"
  • 6. www.luxoft.com Let’s make it look nice const log = ([strings]) => console.log(string); log `Entering log data` // Prints "Entering log data" That’s better
  • 7. www.luxoft.com What about variables? const log = ([string]) => console.log(string); log `Entering log data` // Prints "Entering log data“ log `Entered variable: ${1}` // Prints "Entered variable: " //Fix const log = ([string], data) => console.log(string, data); log `Entered variable: ${1}` // Prints "Entered variable: 1" Що трапилось? Всі змінні передаються у шаблонну функцію, як аргументи. Зазвичай нам потрібно зробити щось більше, ніж надрукувати всі строки разом.
  • 8. www.luxoft.com Let’s make it universal const log = (strings, ...values) => console.log(strings.reduce( (str, value, index) => str += value + (values[index] || '') , '')) log `Welcome to ${new Date().getFullYear()} Your local date is: ${new Date}` //Welcome to 2018 //Your local date is: Mon Dec 03 2018 20:45:59 GMT+0200 (Eastern European Standard Time)
  • 9. www.luxoft.com Use it as i18n // default i18n `Hello ${'World'}` // "Hello World" // we switch to German i18n.locale = 'de'; // but we still write in English i18n`Hello ${'World'}` // "Hallo World" i18n.locale = 'it'; i18n `Hello ${'World'}` // Ciao World i18n.locale = 'sp'; i18n `Hello ${'World'}` // Hola World https://codeburst.io/easy-i18n-in-10-lines-of-javascript-poc-eb9e5444d71e
  • 10. www.luxoft.com Use it for a SQL queries const SQL = require('sql-template-strings') const book = 'harry potter' const author = 'J. K. Rowling' // sequelize: sequelize.query('SELECT author FROM books WHERE name = ? AND author = ?', {replacements: [book, author]}) // is equivalent to sequelize.query(SQL `SELECT author FROM books WHERE name = ${book} AND author = ${author}`) https://github.com/felixfbecker/node-sql-template-strings
  • 11. www.luxoft.com Or slightly modify to be more advanced //If we slightly modify this const SQL = require('sql-query') const Sequelize = require('sequelize') SQL.db = new Sequelize('mysql://user:pass@example.com:9821/db_name') const results = await SQL `SELECT author FROM books WHERE name = ${book} AND author = ${author}` () https://github.com/felixfbecker/node-sql-template-strings
  • 12. www.luxoft.com Create a shorthand for your configs function _get([key], object) { if (object) { return _.get(object, key); } return (object, defValue) => _.get(object, key, defValue); } let config = { author: 'Yuriy Voziy', company: { name: 'Luxoft', url: 'https://career.luxoft.com', office: { rad: { name: 'Irva', address: 'Rad 1014' } } } } _get `company.office.rad.name` (config, 'Dafault') //Irva _get `company.of_fice.rad.name` (config) || 'Default' //Default _get `company.office.rad.name${config}`; // Irva
  • 13. www.luxoft.com Use a shorthand for your nested JSONs function _get([key], object) { if (object) { return _.get(object, key); } return (object, defValue) => _.get(object, key, defValue); } let config = { author: 'Yuriy Voziy', company: { name: 'Luxoft', url: 'https://career.luxoft.com', office: { rad: { name: 'Irva', address: 'Rad 1014' } } } } _get `company.office.rad.name` (config, 'Dafault') //Irva _get `company.of_fice.rad.name` (config) || 'Default' //Default _get `company.office.rad.name${config}`; // Irva
  • 14. www.luxoft.com Or create a wrapper for the configs let config = { author: 'Yuriy Voziy', company: { name: 'Luxoft', url: 'https://career.luxoft.com' } } _get.wrap = function (object) { return ([key], keyv) => _.get(object, key || keyv); } _config = _get.wrap(config); log `${ _config `company.name` }` //Luxoft log `${ _config `company.url` }` //https://career.Luxoft.com
  • 15. www.luxoft.com Fetching urls _fetch = ([url], urlv) => fetch(url || urlv); //This is just to make _fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0` //and _fetch `${_config `site.url`}` //and fetch (_config `site.url`) //Work the same
  • 16. www.luxoft.com But it returns Promise inside a Promise //But this returns promise inside promise ☹ Promise {<pending>} __proto__: Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]: Response body: ReadableStream locked: false __proto__: Object bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "OK" type: "basic" url: "http://www.mocky.io/v2/5c058daf3300005f01e812e0" __proto__: Response
  • 17. www.luxoft.com So let’s make comfort of this //Most of the times we want data, so let's wait for it _fetch = ([url], ...[urlv]) => new Promise((resolve, reject) => fetch(url || urlv).then((response) => resolve(response.json())).catch(reject) ); await _fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0` //{hello: {my: 'world’}} await _fetch `${ _config `site.url` }` //{hello: {my: 'world'}} //Still no HEAD, POST, PUT, DELETE and other header though…
  • 18. www.luxoft.com And add some comfort and possibilities _fetch = ([url, urlb], ...[urlv, options]) => new Promise((resolve, reject) => fetch(url || urlb || urlv, typeof urlv == 'string' ? options : urlv) .then((response) => resolve(response.json())) .catch(reject)); _fetch.options = ([url], ...[urlv]) => ([], ...[options]) => _fetch `${url || urlv}${options}`; const options = {method: 'post'} const resp = _fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0` .then(console.log) .catch(console.error) const resp = await _fetch `http://www.mocky.io/v2/5c058daf3300005f01e812e0 ${options}` const resp = await _fetch `${options} http://www.mocky.io/v2/5c058daf3300005f01e812e0` const resp = await _fetch.options(options) `http://www.mocky.io/v2/5c058daf3300005f01e812e0` log `${ _get `my.deep.value` `${await _fetch(options) `http://www.mocky.io/v2/5c058daf3300005f01e812e0`}`}` log `${ _get `my.deep.value` (resp)}`
  • 19. www.luxoft.com Dependency injection require = require('req') const {log, i18n, _get, _fetch} = require `utils` const Sequelize = require `sequelize` const {dependency, inject, dependencies} = require `di` const lodash = require `lodash` const _config = _get.wrap(require `config`) dependency `db` (new Sequelize( _config `db.string `)) dependency `sql` (require `sql-query`) dependency `log ${log}` dependency `fetch` (require `node-fetch`) dependency `_ ${lodash}` const {log, SQL, _fetch} = dependencies('log', 'sql', '_fetch') const resp = await _fetch `${ _config `site.url` } ${ _config `site.options` }` SQL `INSERT INTO myvalues (${ _get `my.deep.value` (resp) }, ${ _get `hello` (resp)} )` () .then( (v) => inject `log` `${ i18n `Successfully inserted record: ${v}` }`) .catch(console.error.bind(null, i18n `Error inserting value: `, v))