-
-
Save khex/45b14213c9e7e42854f20fb15605efba to your computer and use it in GitHub Desktop.
Elm Client, Node Server , Mongo DB, Mongoose ODM - Get Users and Post User
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Html exposing (..) | |
| import Html.Attributes exposing (..) | |
| import Html.Events exposing (..) | |
| import Http | |
| import Json.Decode as Decode | |
| import Json.Encode as Encode | |
| main = | |
| Html.program | |
| { init = init | |
| , view = view | |
| , update = update | |
| , subscriptions = subscriptions | |
| } | |
| -- MODEL | |
| type alias User = | |
| { id : String | |
| , name : String | |
| , age : Int | |
| , comments: String | |
| } | |
| type alias Model = | |
| { users : List User | |
| , isFetching: Bool | |
| } | |
| init : (Model, Cmd Msg) | |
| init = | |
| ( { users = [], isFetching = False } | |
| , Cmd.none | |
| ) | |
| -- UPDATE | |
| type Msg | |
| = FetchUsers | |
| | CreateUser | |
| | ReceivedUsers (Result Http.Error (List User)) | |
| | UserCreated (Result Http.Error (User)) | |
| user1 : User | |
| user1 = | |
| { id = "" | |
| , name = "Reactjs" | |
| , age = 1 | |
| , comments = "Trying to make POST request from ELM." | |
| } | |
| update : Msg -> Model -> (Model, Cmd Msg) | |
| update msg model = | |
| case msg of | |
| FetchUsers -> | |
| ({ model | isFetching = True }, fetchUsersHttpGet) | |
| CreateUser -> | |
| (model, createUserHttpPost user1) | |
| UserCreated (Ok user) -> | |
| let | |
| _ = Debug.log "user created" user | |
| in | |
| (model, Cmd.none) | |
| UserCreated (Err err) -> | |
| let | |
| _ = Debug.log "Error while Use creation" err | |
| in | |
| (model, Cmd.none) | |
| ReceivedUsers (Ok users) -> | |
| let | |
| _ = Debug.log "users" users | |
| in | |
| ({ model | isFetching = False, users = users }, Cmd.none) | |
| ReceivedUsers (Err err) -> | |
| let | |
| _ = Debug.log "users" err | |
| in | |
| (model, Cmd.none) | |
| -- HTTP | |
| -- FETCH USERS | |
| fetchUsersHttpGet : Cmd Msg | |
| fetchUsersHttpGet = | |
| let | |
| url = | |
| "http://localhost:8080/api/users" | |
| in | |
| Http.send ReceivedUsers (Http.get url decodeUsers) | |
| decodeUsers : Decode.Decoder (List User) | |
| decodeUsers = | |
| Decode.list decodeUser | |
| decodeUser : Decode.Decoder (User) | |
| decodeUser = | |
| Decode.map4 User | |
| (Decode.field "_id" Decode.string) | |
| (Decode.field "name" Decode.string) | |
| (Decode.field "age" Decode.int) | |
| (Decode.field "comments" Decode.string) | |
| -- CREATE USER | |
| createUserHttpPost : User -> Cmd Msg | |
| createUserHttpPost user = | |
| let | |
| url = | |
| "http://localhost:8080/api/users" | |
| body = | |
| user | |
| |> encodeUser | |
| |> Http.jsonBody | |
| in | |
| Http.send UserCreated (Http.post url body decodeUser) | |
| encodeUser : User -> Encode.Value | |
| encodeUser model = | |
| Encode.object | |
| [ ("name", Encode.string model.name) | |
| , ("age", Encode.int model.age) | |
| , ("comments", Encode.string model.comments) | |
| ] | |
| -- VIEW | |
| view : Model -> Html Msg | |
| view model = | |
| div [] | |
| [ | |
| div [] [model.isFetching |> toString |> text] | |
| , br [] [] | |
| , button [ onClick (FetchUsers) ] [ text "Fetch Users" ] | |
| , button [ onClick (CreateUser) ] [ text "Create a User" ] | |
| , br [] [] | |
| , div [] (List.indexedMap (\index user -> (viewUser index user)) model.users) | |
| ] | |
| viewUser: Int -> User -> Html Msg | |
| viewUser index user = | |
| div [] [ | |
| br [] [] | |
| , div[] [text user.id] | |
| , div[] [text user.name] | |
| , div[] [text (toString user.age)] | |
| , div[] [text user.comments] | |
| , br [] [] | |
| , br [] [] | |
| ] | |
| -- SUBSCRIPTIONS | |
| subscriptions : Model -> Sub Msg | |
| subscriptions model = | |
| Sub.none |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // BASE SETUP | |
| // ============================================================================= | |
| // call the packages we need | |
| var express = require('express'); // call express | |
| var app = express(); // define our app using express | |
| var bodyParser = require('body-parser'); | |
| var mongoose = require('mongoose'); | |
| mongoose.connect('mongodb://localhost:27017/restApi'); // connect to our database | |
| var mongoose = require('mongoose'); | |
| var Schema = mongoose.Schema; | |
| var UserSchema = new Schema({ | |
| name: String, | |
| age: Number, | |
| comments: String | |
| }); | |
| var User = mongoose.model('User', UserSchema); | |
| // Add headers to work with elm-reactor | |
| app.use((req, res, next) => { | |
| res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000'); | |
| res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS'); | |
| res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); | |
| res.setHeader('Access-Control-Allow-Credentials', true); | |
| next(); | |
| }); | |
| // configure app to use bodyParser() | |
| // this will let us get the data from a POST | |
| app.use(bodyParser.urlencoded({ extended: true })); | |
| app.use(bodyParser.json()); | |
| var port = process.env.PORT || 8080; // set our port | |
| // ROUTES FOR OUR API | |
| // ============================================================================= | |
| var router = express.Router(); // get an instance of the express Router | |
| // ROUTES FOR OUR API | |
| // ============================================================================= | |
| var router = express.Router(); // get an instance of the express Router | |
| // middleware to use for all requests | |
| router.use(function(req, res, next) { | |
| // do logging | |
| console.log('Something is happening.'); | |
| next(); // make sure we go to the next routes and don't stop here | |
| }); | |
| // test route to make sure everything is working (accessed at GET http://localhost:8080/api) | |
| router.get('/', function(req, res) { | |
| res.json({ message: 'hooray! welcome to our api!' }); | |
| }); | |
| router.route('/users') | |
| // create a user (accessed at POST http://localhost:8080/api/users) | |
| .post(function(req, res) { | |
| var user = new User(); // create a new instance of the User model | |
| user.name = req.body.name; // set the users name (comes from the request) | |
| user.age = req.body.age; // set the users name (comes from the request) | |
| user.comments = req.body.comments; // set the users name (comes from the request) | |
| // save the user and check for errors | |
| user.save(function(err) { | |
| if (err) | |
| res.send(err); | |
| res.json({ message: 'User created!' }); | |
| }); | |
| }) | |
| // get all the users (accessed at GET http://localhost:8080/api/users) | |
| .get(function(req, res) { | |
| User.find(function(err, users) { | |
| if (err) | |
| res.send(err); | |
| res.json(users); | |
| }); | |
| }); | |
| router.route('/users/:user_id') | |
| // get the user with that id (accessed at GET http://localhost:8080/api/users/:user_id) | |
| .get(function(req, res) { | |
| User.findById(req.params.user_id, function(err, user) { | |
| if (err) | |
| res.send(err); | |
| res.json(user); | |
| }); | |
| }) | |
| // update the user with this id (accessed at PUT http://localhost:8080/api/users/:user_id) | |
| .put(function(req, res) { | |
| // use our user model to find the user we want | |
| User.findById(req.params.user_id, function(err, user) { | |
| if (err) | |
| res.send(err); | |
| user.name = req.body.name; // update the users info | |
| user.age = req.body.age; // update the users info | |
| user.comments = req.body.comments; // update the users info | |
| // save the user | |
| user.save(function(err) { | |
| if (err) | |
| res.send(err); | |
| res.json({ message: 'User updated!' }); | |
| }); | |
| }); | |
| }) | |
| // delete the user with this id (accessed at DELETE http://localhost:8080/api/users/:user_id) | |
| .delete(function(req, res) { | |
| User.remove({ | |
| _id: req.params.user_id | |
| }, function(err, user) { | |
| if (err) | |
| res.send(err); | |
| res.json({ message: 'Successfully deleted' }); | |
| }); | |
| }); | |
| // more routes for our API will happen here | |
| // REGISTER OUR ROUTES ------------------------------- | |
| // all of our routes will be prefixed with /api | |
| app.use('/api', router); | |
| // START THE SERVER | |
| // ============================================================================= | |
| app.listen(port); | |
| console.log('Magic happens on port ' + port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment