Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
楽しいProxy
Search
Ryo Nakamura
December 20, 2018
Programming
2
110
楽しいProxy
Proxy is so much fun! @We are JavaScripters! #27
Ryo Nakamura
December 20, 2018
Tweet
Share
More Decks by Ryo Nakamura
See All by Ryo Nakamura
やさしい仮想DOM
ryonkmr
1
200
Other Decks in Programming
See All in Programming
シールドクラスをはじめよう / Getting Started with Sealed Classes
mackey0225
3
410
Macとオーディオ再生 2024/11/02
yusukeito
0
270
Vue.js学習の振り返り
hiro_xre
2
130
とにかくAWS GameDay!AWSは世界の共通言語! / Anyway, AWS GameDay! AWS is the world's lingua franca!
seike460
PRO
1
680
RailsのPull requestsのレビューの時に私が考えていること
yahonda
5
2.3k
OpenTelemetryでRailsのパフォーマンス分析を始めてみよう(KoR2024)
ymtdzzz
5
1.8k
推し活としてのrails new/oshikatsu_ha_iizo
sakahukamaki
3
1.8k
PHP でアセンブリ言語のように書く技術
memory1994
PRO
1
150
Progressive Web Apps für Desktop und Mobile mit Angular (Hands-on)
christianliebel
PRO
0
110
推し活の ハイトラフィックに立ち向かう Railsとアーキテクチャ - Kaigi on Rails 2024
falcon8823
6
2.4k
カスタムしながら理解するGraphQL Connection
yanagii
1
1.4k
Golang と Erlang
taiyow
8
1.9k
Featured
See All Featured
Building an army of robots
kneath
302
42k
Automating Front-end Workflow
addyosmani
1366
200k
Happy Clients
brianwarren
97
6.7k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
126
18k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
47
5k
What's in a price? How to price your products and services
michaelherold
243
12k
Building a Modern Day E-commerce SEO Strategy
aleyda
38
6.9k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
46
2.1k
The Straight Up "How To Draw Better" Workshop
denniskardys
232
140k
Fashionably flexible responsive web design (full day workshop)
malarkey
404
65k
The Power of CSS Pseudo Elements
geoffreycrofte
72
5.3k
Product Roadmaps are Hard
iamctodd
PRO
48
10k
Transcript
RyoNkmr PROJECT DATE PRESENTER 2018-12-20 ָ͍͠Proxy @WE ARE JAVASCRIPTERS! #27
ࣗݾհ • RyoNkmr • @RyoNkmr_ • Retty Inc. • JavaScript
3ੜ • ॳొஃ
ָ͍͠ Proxy
Proxy
...͜ΕΒجຊతͳݴޠૢ࡞ʢྫ ͑ɺϓϩύςΟݕࡧɺೖɺྻ ڍɺؔݺͼग़͠ͳͲʣʹׂΓࠐ Έɺಈ࡞ΛΧελϚΠζͰ͖·͢ɻ [ϝλϓϩάϥϛϯά | MDN](https:// developer.mozilla.org/ja/docs/Web/ JavaScript/Guide/ Meta_programming)
Proxy
ରԠঢ়گ
https://caniuse.com/#search=proxy
https://node.green/#ES2015-built-ins-Proxy
Browser: IE11Ҏ֎ Node: v6.4.0Ҏ߱ ରԠঢ়گ
Proxyͱͷग़ձ͍
ͱ͋Δݱͷ Pull Request { type: Array, validate(values) { return values.length
!== 0; }, }
(ϨϏϡΞʔ) { type: Array, validate(values) { return values.length !== 0;
}, } const fakeData = { length : 1000 }; ͜ΕͰಥഁͰ͖ΔͷͰɾɾɾʁ(Request Changes)
{ type: Array, validate(values) { return Array.isArray(values) && values.length !==
0; }, }
(ϨϏϡΞʔ) { type: Array, validate(values) { return Array.isArray(values) &&
values.length !== 0; }, }
(ϨϏϡΞʔ) const fakeData = new Proxy([], { get(...args) { if
(args[1] === 'length') { return -100000000000; } return Reflect.get(...args); } }); > fakeData.length // -100000000000 > Array.isArray(fakeData) // true ͜ΕͰಥഁͰ͖ΔͷͰɾɾɾʁ(Request Changes) { type: Array, validate(values) { return Array.isArray(values) && values.length !== 0; }, }
{ type: Array, validate(values) { return Array.isArray(values) && values.length >
0; }, }
Proxy
͓ͪΌͰɾɾɾʁ
None
͍ಓΛߟ͑ͯΈΔ
ॲཧΛࠩ͠ࠐΉ
Logger on a Node.js Application
module.exports = new Proxy(console, { get(target, prop, receiver) { return
(...args) => { require('fs').appendFile('logger.log', `[${prop}]: ${args}`, 'utf8', err => { if (err) { throw err; } }); return Reflect.apply(target[prop], receiver, args); }; } }); console Λ Proxy
> const logger = require('./log.js'); > logger.log('plz log me') plz
log me > logger.error('this is an error!') this is an error! > logger.count('cat') cat: 1 > logger.count('dog') dog: 1 > logger.count('cat') cat: 2 console ͱಉ͡ interface
$ cat logger.log [log]: plz log me [error]: this is
an error! [count]: cat [count]: dog [count]: cat ࣮ߦ࣌ʹϑΝΠϧʹॻ͖ग़͢
Get Λ Proxy ͯ͠༡Ϳ
ແݶϝιουνΣʔϯ > https://www.keithcirkel.co.uk/metaprogramming-in-es6- part-3-proxies/
module.exports = (domain = 'google.com') => { let paths =
[]; // ঢ়ଶΛ͓࣋ͬͯ͘ // ঢ়ଶΛݩʹURLจࣈྻΛΈཱͯΔؔͷఆٛ const buildUrl = () => { const _paths = [...paths]; paths = []; return `https://${domain}/${_paths.join('/')}`; }; return new Proxy(buildUrl, { get(_, prop, receiver) { // propertyΞΫηεΛঢ়ଶͷมߋʹ͏ paths = [...paths, prop]; // chaining͢ΔͨΊʹProxyࣗΛฦͯ͋͛͠Δ return receiver; }, }); };
const urlBuilder = require('./urlBuilder.js'); const google = urlBuilder('www.google.co.jp'); > google.image.saikyo.engineer.wannabe();
'https://www.google.co.jp/image/saikyo/engineer/wannabe' > google.search.cool.javascripters(); 'https://www.google.co.jp/search/cool/javascripters' method missing Ά͍͜ͱ͕Ͱ͖Δ
Array Λ Proxy ͯ͠༡Ϳ
Πέϝϯͳ Array
const parsePropName = prefixCool => { const [, name] =
/^cool(\w+)/.exec(prefixCool) || [, null]; return name !== null ? `${name[0].toLowerCase()}${name.slice(1)}` : prefixCool; } module.exports = ({ goodLooking } = { goodLooking: false }) => ( new Proxy([], { get(target, prop, receiver) { const actualPropName = parsePropName(prop); if ( typeof target[actualPropName] !== 'function' || goodLooking || prop.startsWith('cool') ) { return Reflect.get(target, actualPropName, receiver); } throw new TypeError(`Hmm... You'are not my type`); } }) );
> const coolArray = require('./coolArray.js')(); undefined > coolArray.push('hey, man.'); TypeError:
Hmm... You'are not my type at Object.get (.../proxy/coolArray.js:18:13) > coolArray.coolPush('hey, handsome man.'); 1 > [...coolArray.coolValues()]; [ 'hey, handsome man.' ] cool͍͍ͬͯͪͪݴΘͳ͍ͱ ݴ͏͜ͱΛฉ͔ͳ͍ArrayΛ࡞ΕΔ
Proxy ָ͍͠
·ͱΊ
• ґଘίʔυΛͦͷ··ʹɺґଘϥΠϒϥ ϦΛࣅͨΑ͏ͳผʹࠩ͠ସ͑Δͱ͖ • ϥΠϒϥϦͱ͔ϑϨʔϜϫʔΫͭ͘Δͱ ͖ • Array.isArray ͕ true
Λฦ͢ͷʹ length ͩ ͚͓͔͍͠Λฦ͢ Array Έ͍ͨͳ ͕ͭඞཁͳͱ͖
͝ਗ਼ௌ͋Γ͕ͱ͏͍͟͝·ͨ͠