SlideShare uma empresa Scribd logo
1 de 67
mithril.js + postgREST
to build and consume awesome API’s
Antônio Roberto - ton
twitter.com/_devton
github.com/devton
me
catarse.me
work
github.com/catarse
open
+
+
backend stuff
stack
why we need
• real split front-end / backend
• expands to other devices
• composable middleware
api?
research
+
+ +
backend stuff
stack
github.com/begriffs/postgrest
PostgREST serves a fully RESTful API from any
existing PostgreSQL database. It provides a
cleaner, more standards-compliant, faster API
than you are likely to write from scratch.
begriffs
github.com/begriffs/postgrest
• Versioning
• Authorization
• Serializing JSON responses directly in SQL
Versioning
https://github.com/begriffs/postgrest/wiki/API-Versioning
Versioning
DATABASE SCHEMA
CREATE SCHEMA “2";
GRANT USAGE ON SCHEMA "2" TO PUBLIC;
ALTER DATABASE your_db
SET search_path = "2", "1";
Accept: application/vnd.you.com+json; version=1
Versioning
HTTP REQUEST HEADER
Authorization
https://github.com/begriffs/postgrest/wiki/Security-and-Permissions
Auth
SCHEMA
CREATE SCHEMA postgrest;
SET search_path = postgrest, pg_catalog, “1”;
Auth
TABLE
CREATE TABLE postgrest.auth (
id character varying NOT NULL,
rolname name NOT NULL,
pass character(60) NOT NULL,
CONSTRAINT auth_pkey PRIMARY KEY (id)
) WITH ( OIDS=FALSE );
Auth
HTTP REQUEST
POST /postgrest/users
{
"id": "jdoe",
"pass": "supersecret",
"role": "author"
}
PostgREST exposes the current
user id as user_vars.user_id,
which is a variable we can use
inside triggers and functions.
SELECT current_setting('user_vars.user_id');
begriffs
github.com/begriffs/postgrest
Auth
JSON Web Tokens
POST /postgrest/token
{
"id": "jdoe",
"pass": "supersecret"
}
Auth
JSON Web Tokens
GET /need-auth
Authorization: Bearer [token]
Serializing JSON
Serializing JSON
HTTP REQUEST
GET /team_totals
Serializing JSON
VIEW “1”.team_totals
CREATE OR REPLACE VIEW "1".team_totals as (
select
count(DISTINCT u.id) as member_count,
array_to_json(array_agg(DISTINCT country.name)) as countries,
count(DISTINCT c.project_id)
FILTER (WHERE c.was_confirmed)
as total_contributed_projects,
count(DISTINCT lower(unaccent(u.address_city))) as total_cities,
sum(c.value)
FILTER (WHERE c.was_confirmed)
as total_amount
from users u
left join contributions c on c.user_id = u.id
left join countries country on country.id = u.country_id
where u.admin
);
Serializing JSON
GET /team_totals
[
{
"member_count": 26,
"countries": [
"Austrália",
"Brasil",
"Canadá",
"Dinamarca"
],
"total_contributed_projects": 617,
"total_cities": 12,
"total_amount": 66649.09
}
]
http://mithril.js.org
Mithril is a client-side MVC framework - a tool
to organize code in a way that is easy to think
about and to maintain.
• Only 12kb gzipped, no dependencies
• Virtual DOM diffing and compilable templates
• Intelligent auto-redrawing system
• Hierarchical MVC via components
• Small API, small learning curve
Loading - Rendering
http://mithril.js.org/benchmarks.html
window.c.TeamTotal = ((m, models, _) => {
return {
controller: () => {
// ...
},
view: (ctrl) => {
// ...
}
};
}(window.m, window.c.models, window._));
our component struct
controller
controller: () => {
let teamTotal = m.prop([]);
models.teamTotal.getRow().then(teamTotal);
return {
teamTotals: teamTotals
};
},
view
view: function(ctrl) {
return m('#team-total', [
_.map(ctrl.teamTotals(), (teamTotal) => {
return m('.w-container', [
m('.w-row', [
m('p.fontsize-base', [
'Hoje somos ', teamTotal.member_count,
' pessoas espalhadas por ', teamTotal.total_cities,
' cidades em ', teamTotal.countries.length
])
])
]);
})
]);
}
mithril.postgrest
github.com/catarse/mithril.postgrest
mithril.postgrest
• Help you authenticating in a PostgREST server.
• Provide wrappers arround the mithril request
function to use JWT.
• Provide a constructor for objects that will
interact with PostgREST endpoints
• Provide some helpers to build some useful View-
Model objects.
mithril.postgrest
• Help you authenticating in a PostgREST server.
• Provide wrappers arround the mithril request
function to use JWT.
• Provide a constructor for objects that will
interact with PostgREST endpoints
• Provide some helpers to build some useful View-
Model objects.
Model
mithril.postgrest
let teamTotal = m.postgrest.model(‘team_totals’);
teamTotal.getRow().then((row) => {
console.log('fecthed:', row);
});
filter view models
mithril.postgrest
let filters = m.postgrest.filtersVM({id: ‘eq’}),
users = m.postgrest.model(‘users');
filters.id(7);
users.getPage(filters.parameters()).then((data) => {
console.log('fetched:', data);
})
pagination view model
mithril.postgrest
var userPages = m.postgrest.paginationVM(users.getPageWithToken);
// The firstPage function returns a mithril promise
userPages.firstPage(filters.parameters()).then(() => {
// Results are in collection
console.log(userPages.collection());
},
() => {
alert('Error loading users');
});
* paginationVM(loadPageFunction) - Generate a pagination View-Model that loads pages using
the loadPageFunction (should be a mithril request)
pagination view model
mithril.postgrest
// The nextPage function returns a mithril promise
userPages.nextPage().then(() => {
// Results are appended to collection
console.log(userPages.collection());
},
() => {
alert('Error loading next page');
});
https://github.com/catarse/catarse.js
https://github.com/catarse/catarse
http://silvers.org/pg <- recommended!!
https://github.com/catarse/mithril.postgrest
links
keep going ->
thanks
more
cool
stuff

AHEAD
scenario
project reminder feature
step 1 - routes
project reminder routes
step 1 - routes
project reminder routes
step 2 - view
project reminder view
step 2 - view
project reminder view
postgREST default schema = “1”
check if transaction user is a owner or admin
step 2 - view
project reminder grants
since we are using postgres user role system we need to grant privileges to
roles that you want to given access.
step 2 - view
project reminder functions / triggers
since postgREST implements authentication endpoints and JWT tokens, we need
to prevent that admin or web_user delete all your reminders and create
reminders for other users.
public.insert_project_reminder() trigger
public.delete_project_reminder() trigger
current_setting(‘user_vards.user_id’)
the setting ‘user_vards.user_id’
is set via postgREST has local on transaction
testing requests [POST]
testing requests [GET]
testing requests [DELETE]
last - component
project reminder javascript component
github.com/catarse/catarse.js
this repo handles with all mithril components
c.ProjectReminder
this component should handle with:
- reminder btn render
- insert reminder
- delete reminder
c.ProjectReminder.controller
c.ProjectReminder.controller
c.ProjectReminder.view
mounting Component
mounting project-reminder
http://d.pr/i/15ktg

Mais conteúdo relacionado

Mais procurados

Whats New in MSBuild 3.5 and Team Build 2008
Whats New in MSBuild 3.5 and Team Build 2008Whats New in MSBuild 3.5 and Team Build 2008
Whats New in MSBuild 3.5 and Team Build 2008
wbarthol
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
A Brief Introduce to WSGI
A Brief Introduce to WSGIA Brief Introduce to WSGI
A Brief Introduce to WSGI
Mingli Yuan
 

Mais procurados (20)

Recent Updates at Embulk Meetup #3
Recent Updates at Embulk Meetup #3Recent Updates at Embulk Meetup #3
Recent Updates at Embulk Meetup #3
 
Whats New in MSBuild 3.5 and Team Build 2008
Whats New in MSBuild 3.5 and Team Build 2008Whats New in MSBuild 3.5 and Team Build 2008
Whats New in MSBuild 3.5 and Team Build 2008
 
Embuk internals
Embuk internalsEmbuk internals
Embuk internals
 
Embulk - 進化するバルクデータローダ
Embulk - 進化するバルクデータローダEmbulk - 進化するバルクデータローダ
Embulk - 進化するバルクデータローダ
 
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
ClojureScript - Making Front-End development Fun again - John Stevenson - Cod...
 
A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...
 
Fighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with Embulk
 
Data integration with embulk
Data integration with embulkData integration with embulk
Data integration with embulk
 
Automating Workflows for Analytics Pipelines
Automating Workflows for Analytics PipelinesAutomating Workflows for Analytics Pipelines
Automating Workflows for Analytics Pipelines
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Scripting Embulk Plugins
Scripting Embulk PluginsScripting Embulk Plugins
Scripting Embulk Plugins
 
Gohan
GohanGohan
Gohan
 
REST API for your WP7 App
REST API for your WP7 AppREST API for your WP7 App
REST API for your WP7 App
 
A Brief Introduce to WSGI
A Brief Introduce to WSGIA Brief Introduce to WSGI
A Brief Introduce to WSGI
 
Bosh 2.0
Bosh 2.0Bosh 2.0
Bosh 2.0
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Plproxy
PlproxyPlproxy
Plproxy
 
Fluentd at Bay Area Kubernetes Meetup
Fluentd at Bay Area Kubernetes MeetupFluentd at Bay Area Kubernetes Meetup
Fluentd at Bay Area Kubernetes Meetup
 
Slim Framework
Slim FrameworkSlim Framework
Slim Framework
 

Semelhante a using Mithril.js + postgREST to build and consume API's

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
Ovadiah Myrgorod
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
Bo-Yi Wu
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 

Semelhante a using Mithril.js + postgREST to build and consume API's (20)

Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017
 
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
Maciej Treder ''Angular Universal - a medicine for the Angular + SEO/CDN issu...
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSockets
 
Mvc - Titanium
Mvc - TitaniumMvc - Titanium
Mvc - Titanium
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Vue micro frontend implementation patterns
Vue micro frontend implementation patternsVue micro frontend implementation patterns
Vue micro frontend implementation patterns
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
Reactive Application Using METEOR
Reactive Application Using METEORReactive Application Using METEOR
Reactive Application Using METEOR
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

using Mithril.js + postgREST to build and consume API's