Skip to content

Instantly share code, notes, and snippets.

@sean3z
sean3z / hero.rs
Last active March 17, 2018 16:10
A first stab at our Hero model
#[derive(Serialize, Deserialize)]
pub struct Hero {
pub id: Option<i32>,
pub name: String,
pub identity: String,
pub hometown: String,
pub age: i32
}
@sean3z
sean3z / Cargo.toml
Created March 17, 2018 15:56
Adding serde and rocket_contrib
[package]
name = "hero-api"
version = "0.1.0"
authors = ["sean"]
[dependencies]
rocket = "0.3.6"
rocket_codegen = "0.3.6"
serde = "1.0"
serde_json = "1.0"
@sean3z
sean3z / down.sql
Last active March 18, 2018 03:53
Creating our Heroes schema
-- This file should undo anything in `up.sql`
DROP TABLE heroes;
@sean3z
sean3z / hero.rs
Last active March 18, 2018 03:57
bind our struct to our table
use diesel;
use diesel::prelude::*;
use diesel::mysql::MysqlConnection;
use schema::heroes;
#[table_name = "heroes"]
#[derive(Serialize, Deserialize, Queryable, Insertable)]
pub struct Hero {
pub id: Option<i32>,
pub name: String,
@sean3z
sean3z / app.js
Created March 18, 2018 02:38
pushState and popstate example using jQuery
// when a user clicks one of our links
$('a').click(function (e) {
// Detect if pushState is available
if (history.pushState) {
history.pushState(null, null, $(this).attr('data-location')); // URL is now /inbox/N
// showMailItem(); // example function to do something based on link clicked
}
return false;
@sean3z
sean3z / server.js
Created March 18, 2018 02:42
Websocket example (without Socket.io)
var server = require('websocket').server, http = require('http');
var socket = new server({
httpServer: http.createServer().listen(1337)
});
socket.on('request', function(request) {
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
@sean3z
sean3z / index.html
Created March 18, 2018 02:43
Websocket example (Native websocket)
<div id="content"></div>
<script type="text/javascript">
var content = document.getElementById('content');
var socket = new WebSocket('ws://localhost:1337');
socket.onopen = function () {
socket.send('hello from the client');
};
socket.onmessage = function (message) {
@sean3z
sean3z / schema.rs
Created March 18, 2018 04:51
Diesel schema macro - id Nullable
table! {
heroes {
id -> Nullable<Integer>,
name -> Varchar,
identity -> Varchar,
hometown -> Varchar,
age -> Integer,
}
}
@sean3z
sean3z / db.rs
Created March 18, 2018 04:55
Connection Pooling for Rust/Diesel
use std::ops::Deref;
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use r2d2;
use r2d2_diesel::ConnectionManager;
use diesel::mysql::MysqlConnection;
@sean3z
sean3z / hero.rs
Last active April 3, 2018 17:05
Hero implementation
impl Hero {
pub fn create(hero: Hero, connection: &MysqlConnection) -> Hero {
diesel::insert_into(heroes::table)
.values(&hero)
.execute(connection)
.expect("Error creating new hero");
heroes::table.order(heroes::id.desc()).first(connection).unwrap()
}