Coder Social home page Coder Social logo

zappajs / zappajs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from shimaore/zappajs

192.0 13.0 28.0 1.91 MB

web application framework for node built on express and socket.io, based on mauricemach/zappa

Home Page: https://zappajs.github.io/zappajs/

License: MIT License

CoffeeScript 95.52% HTML 3.39% Shell 1.09%

zappajs's Introduction

Zappa is a CoffeeScript-optimized interface to Express and Socket.IO.

Build Status

Synopsis

require('./zappajs') ->

  ## Server-side ##
  teacup = @teacup

  @get '/': ->
    @render 'index',
      title: 'Zappa!'
      scripts: '/index.js /more.js /client.js'
      stylesheet: '/index.css'

  @view index: ->
    {doctype,html,head,title,script,link,body,h1,div} = teacup
    doctype 5
    html =>
      head =>
        title @title if @title
        for s in @scripts.split ' '
          script src: s
        link rel:'stylesheet', href:@stylesheet
      body ->
        h1 'Welcome to Zappa!'
        div id:'content'
        div id:'content2'

  pixels = 12

  @css '/index.css':
    body:
      font: '12px Helvetica'
    h1:
      color: 'pink'
      height: "#{pixels}px"

  @get '/:name/data.json': ->
    record =
      id: 123
      name: @params.name
      email: "#{@params.name}@example.com"
    @json record

  ## Client-side ##
  @coffee '/index.js': ->
    alert 'hi'

  ## Client-side with Browserify ##
  @with 'client' # requires `zappajs-plugin-client`
  @browser '/more.js': ->
    domready = require 'domready'
    $ = require 'component-dom'
    domready ->
      $('#content').html 'Ready to roll!'

  ## Client-side with ExpressJS/Socket.IO session sharing ##
  @use session:
    store: new @session.MemoryStore()
    secret: 'foo'
    resave: true, saveUninitialized: true

  @on 'ready': ->
    console.log "Client #{@id} is ready and says #{@data}."
    @emit 'ok', null

  @client '/client.js': ->
    @emit 'ready', 'hello'
    $ = require 'component-dom'
    @on 'ok', ->
      $('#content2').html 'Ready to roll too!'

Install

npm install zappajs

Other resources

ZappaJS 5.0 Changes

Removal of browserify dependency

@browser and @isomorph are now in the client module, alongside @client.

ZappaJS 4.0 Changes

Major improvements in Socket.IO interface:

Now supports saving the Session object in Socket.IO methods. Session content can be modified both from ExpressJS and from Socket.IO.

Supports ack callback for all Socket.IO emit calls.

Embedded client-side code:

The ZappaJS client is no longer embedded and was moved to a separate module, zappajs-client.

Sammy and jQuery are no longer embedded:

  • As a consequence the zappa middleware is no longer required and was removed. If your code references any Javascript file under /zappa/, consider using e.g. browserify-middleware to build the dependencies.
  • Also, @client and @shared are gone (along with their magic).

Client-side code is now bundled using browserify-string; @browser is available alongside @client, while @isomorph replaces @shared.

New features

Now uses the debug module instead of logging to console directly.

Host and port might be specified using the ZAPPA_PORT and ZAPPA_HOST environment variables, which are used as default if no explicit configuration is provided.

zappajs's People

Contributors

agnoster avatar aldonline avatar atifaziz avatar audreyt avatar creatorrr avatar datashaman avatar dvv avatar edubkendo avatar esamattis avatar mauricemach avatar rachel-carvalho avatar scien avatar shimaore avatar smathy avatar timshadel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zappajs's Issues

Session trouble

Hi!

I'm having a hard time working with sessions. Before I found zappajs I used just expressjs. Express.js have an example of how to work with sessions to create basic authentication:

https://github.com/visionmedia/express/blob/master/examples/auth/app.js

I tried to do that in zappa with no luck. I use it like this:

@use 'bodyParser',  'cookieParser': {secret: 'shhhh, very secret'}, 'session': {secret: 'shhhh, very secret'}

But I never seem to have access to the session. I'm sure that I'm just doing it wrong, sorry for my lack of skills. It would be awesome to have an example likte that one.

Integrate `forever`

[suggested by @scien]
integrate forever so you could do something like

require('zappa').daemon 3000, ->

or

{@app} = require('./zappa'),
@app.daemonize 'log.txt', 'error.txt'

Adding Express Validator

Hey,

I'm thinking about adding Express Validator to Zappa. I wrote a blog post about the sugar I'm using to make it nice.

Adding it straight into zappa will make two functions available @assert and @sanitize. I can also add support for socket.io.

Any thoughts on how the API should look like?

@get '/health', ->
  @on_error = @next # This is the error handler,
                                   # if asserting goes wrong, next()
                                   # is the default express error handler,
                                   # and @on_error should be equal to
                                   # next by default
  @pre =>
    @assert('param', 'Invalid Param').notEmpty()
  , =>
    # Validation Passed
    @response.json
      pid: process.pid
      memory: process.memoryUsage()
      uptime: process.uptime()

Also: the github fork this project link in Zappa's website is broken, and leads to the wrong repo.

CoffeeCup

Replace CoffeeKup with CoffeeCup?

@title, etc. don't work anymore

Express 3.x does not provide a way to retrieve the options set after it was processed by an engine; and it create a new, private copy of the one we pass to it.

Therefor well-documented Zappa features like @title, etc., don't work anymore in Express 3.x.

Array middleware problem

Consider stuff like:

common = [foo, bar, baz]
@get '/something', common, fn

I want to use array middleware like express, but this turn out to be an error:

TypeError: Object function (){
       this.next();
    },function (){
       this.next();
    },function (){
       this.next();
    } has no method 'apply'

TypeError: Property 'engine' of object #<View> is not a function

TypeError: Property 'engine' of object #<View> is not a function
    at View.render (/home/c/node_modules/zappajs/node_modules/express/lib/view.js:75:8)
    at Function.app.render (/home/c/node_modules/zappajs/node_modules/express/lib/application.js:505:10)

Just did npm update and am now getting that ^, even using the following zappajs example:


    @set 'view engine': 'eco'

    @get '/': -> @render index: {foo: 'bar', title: 'Eco template'}
    @get '/jade': -> @render 'index.jade': {foo: 'bar', title: 'Jade template'}

    @view index: '''
      <h1><%= @title %></h1>
      <p><%= @foo %></p>
    '''

    @view layout: '''
      <!DOCTYPE html>
      <html>
        <head><title><%= @title %></title></head>
        <body><%- @body %></body>
      </html>
    '''

    @view 'index.jade': '''
      h1= title
      p= foo
    '''

    @view 'layout.jade': '''
      !!! 5
      html
        head
          title= title
        body!= body
    '''

no such file or directory zappajs/vendor/jquery-1.8.3.min.js

Hello,

I've just installed the default (stable?) zappajs module, globally (also tested locally, same results),
using npm install -g zappajs

seems it worked:

however when I try to execute this sample:

require('zappajs') ->
  @get '/hi': 'hi'

I get:

Error: ENOENT, no such file or directory '/usr/local/lib/node_modules/zappajs/vendor/jquery-1.8.3.min.js'
    at Object.fs.openSync (fs.js:338:18)
    at Object.fs.readFileSync (fs.js:182:15)
    at vendor (/usr/local/lib/node_modules/zappajs/lib/zappa.js:22:15)
    at Object.<anonymous> (/usr/local/lib/node_modules/zappajs/lib/zappa.js:25:12)
    at Object.<anonymous> (/usr/local/lib/node_modules/zappajs/lib/zappa.js:1044:4)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)

I looked at this /vendor dir, and indeed there are only:

     sammy-0.7.2.min.js 
     socket.io.min.js

no jquery. however I don't know which side is right, the code or the folder :)

@include doesn't work

calling @include "./some.coffee"
results in Cannot find module ... /.zappa-a7973752-2bc4-48ca-9294-2bdba413aea6/some.coffee.

looking at the source require(path.join(context.root, p)) is used.
replacing it with require(path.join(context.real_root, p)) resolves that error.

Zappajs with Express 3.x

I've spent some time today, playing with Zappajs and Express 3 and I've published my first results :
https://github.com/Hypee/zappajs/tree/express_3

The management of template engines has totally changed in Express 3, for now I've activated CoffeeKup, Eco and Jade engines, but we have to find a way to make that more dynamic.

Layouts and Partials are gone in Express 3, so tests using them are failing.
Socket.io isn't working, I didn't take a look yet.

Backporting maurimach/zappa's pull requests

Here's the list of pull requests from mauricemach/zappa and their current status wrt zappajs/zappajs

Applied But Incomplete

Applied, Can Close

Not Needed

  • mauricemach#95 is pretty extensive, needs to be tested (and maybe updated), adds dependency, but would solve mauricemach#79 -- and not needed anymore, connect-assets does the job (add jquery, sammy, and Zappa's client.js to the assets to get a single-file download, or use the recent /zappa/Zappajs download).
  • mauricemach#102 needs some minor work -- not needed, databag is no longer supported that way

Better integrated client-side templating

[suggested by @scien]

Right now my run script compiles, combines, and minifies my coffeecup templates, then i just serve the file up in a static dir. Would be nice to be able to just host these from a @client.
To assist with this, @include might be a nice feature inside @client. Currently if i want to organize my code in multiple files, i'd have to serve them from different urls.

Link Express and Socket.IO

[Follow-up from conversation in #8 ]

@scien the issue as I understand it is that the (server-side) sessions inside Express and inside Socket.IO are independent, so for example you can't do:

@get '/emit': ->
    # Express session has access to the proper socket for that client.
    @emit 'username':@session.username

@on 'connect': ->
   # Socket.IO has access to the Express session.
   @emit 'username': @session.username

So the idea (at least) would to be able to provide @emit inside an Express context, and @session inside a Socket.IO context.

The solution I referenced essentially does:

  1. client first connects to the socket server (to obtain socket ID);
  2. client queries Zappa (via Express) (with socket ID and desired Socket.IO channel name); Zappa returns authentication token and stores the mapping between the socket ID and the Express session (so that it can retrieve the Express session from the socket session, server-side); and stores the session ID in the Express session.
  3. client subscribes to channel using the authentication token.

Error: Cannot find module 'zappajs' 0.4.3

I can't run coffee hi.coffee

Error: Cannot find module 'zappajs'
at Function._resolveFilename (module.js:337:11)
at Function._load (module.js:279:25)
at Module.require (module.js:359:17)
at require (module.js:375:17)
at Object. (/Users/ap/hi.coffee:3:3)
at Object. (/Users/ap/hi.coffee:9:4)
at Module._compile (module.js:446:26)
at Object.run (/usr/lib/nodejs/coffee-script/lib/coffee-script/coffee-script.js:68:25)
at /usr/lib/nodejs/coffee-script/lib/coffee-script/command.js:135:29
at /usr/lib/nodejs/coffee-script/lib/coffee-script/command.js:110:18

Change Dependency on Express 3.0.x to a fixed version

Hi,

"dependencies": {
    "express": "3.0.x",
    "socket.io": "0.9.x",
    "coffeecup": "0.3.x",
    "uglify-js": "1.1.x"
  }

The current dependency on Express 3.0.x is problematic, breaking changes to Express are passing through unexpectedly.

For example, we use Zappa 0.4.0 and an npm install on a new machine just gave us Express with the new json/jsonp separation that we haven't implemented. So, everything broke down.

Not everyone is using semantic versioning, stuff will break, we need a clear dependency for each version of Zappa.

Express Server listening on port NaN

Express server listening on port NaN in development mode
Zappa 0.4.10 "Freak Out!" orchestrating the show

I get NaN when using cluster (obviously) and in some of the tests.

client-side @on after domready

the following logs "bar1" and "bar2"

My understanding from this is that you can't add a new event after the dom is ready. This stackoverflow thread had the same problem (http://stackoverflow.com/questions/6483862/socket-io-server-emits-not-firing).

Is there anyway to accomplish this? I want to listen for new events in reaction to a user's actions.

require('./zappajs') ->

  @get '/': ->
    @render index: {layout: no}

  @on foo: ->
    @emit "bar#{n}", {} for n in [1..5]

  @client '/index.js': ->
    @connect()

    _io = @
    @on bar1: ->
      console.log 'bar1'

    class Outer1
      constructor: ->
        _io.on bar2: ->
          console.log 'bar2'
    class Outer2
      constructor: ->
        _io.on bar3: ->
          console.log 'bar3'

    new Outer1()
    $ ->
      new Outer2()

      _io.on bar4: ->
        console.log 'bar4'

      class Inner
        constructor: ->
          _io.on bar5: ->
            console.log 'bar5'
      new Inner()

      _io.emit 'foo', {}

  @view index: ->
    doctype 5
    html ->
      head ->
        script src: '/zappa/Zappa-simple.js'
        script src: '/index.js'

Update Zappa's Synopsis

Zappa has changed quite a bit, but the synopsis in the README is still the same. For example, there's no @swap:

@get '#/': ->
      @swap 'Ready to roll!'

(also: sorry for being busy this weekend, had an unexpected terror attack. @shimaore can I be a collaborator on the template project?)

Add an easy way to add things to context

Again, this is pretty straightforward and I can do this, just want your go ahead before I plunge into the code.

We only need to add a @context var that will enable us to reference the context and add more functionality to it. This will improve the DSL quality of Zappa, as we can add @assert with this, and @check and @create @job 'somejob', ['arg', 'u', 'ments'] without having to change zappa itself. I constantly find new ways to improve Zappa for my usage, like adding winston logging with @error and @log but there's no easy way to add them.

favicon middleware won't load

I'm seeing the same behavior I saw with socket.io when originally upgrading to 0.4.x. server just hangs trying to load the resource. You fixed socket.io with 0.4.5, what was the issue that time?

@app.use @express.favicon 'path_to_icon.ico'

Plugins

I'm going to add experimental support for plugins to Zappa. These would be e.g. like Validator in #36.
Hopefully people will find interesting uses for plugins as well.

Objectives

My first target will be a plugin or multiple plugins for CSS; this would also allow to remove things like @stylus, @less, etc. out of core Zappa, and move them into plugins; which would eliminate the css option to Zappa.run(). This could also automate dependencies -- stylus would be a dependency of zappajs-stylus, etc.

require('zappajs') ->
  @plugin `zappajs-stylus`

  @stylus '/index.css': ...

I guess a generic solution (equivalent to the current css option) would be:

require('zappajs') ->
  @plugin 'zappajs-css', 'stylus'

(in which case the developer still needs to provide the stylus package).

Plugin structure

A plugin will be anything that can be required, whether it's a package in node_modules or a file. They'll work kinda like @include, but have access to some Zappa internals:

# zappajs-validator.coffee
@plugin ->
  @helper 'assert' -> ...

A plugin will receive at least one argument, an object containing context (same as @) and (for now) route (allows to add a native Zappa route -- I need this to do the CSS plugin thing). Extra arguments provide by the developer are also provided.

Zappajs 0.4, restoring "partial" functionality

The following code is working in ZappaJS 0.3.9 but not in ZappaJS 0.4.0 due to the migration from Express 2 to Express 3 where "partial" functionality has been removed.

#
# Installed : 
# npm install [email protected] (working) or npm install [email protected] (non working)
# npm install eco
#

require('zappajs') ->

    #
    # CoffeeCup views
    #
    @view 'header': ->
        head ->
            "I'm the header"

    @view 'footer': ->
        p ->
            "I'm the footer"

    @view 'page': ->
        partial 'header'
        p ->
            text "I'm the body"
        partial 'footer'

    #
    # Eco views
    #
    @view 'header.eco': 
        '''
        <head>
            I'm the header
        </head>
        '''

    @view 'footer.eco': 
        '''
        <p>
            I'm the footer
        </p>
        '''

    @view 'page.eco': 
        '''
        <%- @partial 'header.eco' %>
        <p>I'm the body</p>
        <%- @partial 'footer.eco' %>
        '''

    #
    # Routes
    #

    # CoffeeCup page
    @get '/': ->
        @render 'page', {layout:false}

    # Eco page
    @get '/eco': ->
        @render 'page.eco', {layout:false}

An Express 3 middleware project is restoring the "partial" functionality (https://github.com/publicclass/express-partials) but it's currently limited to EJS templates.

Cleanup docs

  • Remove old (0.2.x-related) documentation.
  • Update examples to refer to CoffeeCup.

@all for Express

@app.all '/api/v1/user/current/*', (req, res, next) ->
    if req.user then next()
    else res.end()

Just noticed there's no @all function. Should I write a pull request or is that intentional?

Including Files in Included files

Hi,

So we got our main app:

# index.coffee
@include './config/initialize'

And then in initialize we also include other files

# initialize.coffee
@include = ->
    @include './initializers/express.coffee'
    @include './initializers/sockets.coffee'

Include will try to require /initializers/express.coffee, not config/initializers/express.coffee.

The reason is that @include uses index.coffee as the root:

context.root = path.dirname(module.parent.filename)

Instead of recalculating it whenever it tries to include stuff.

@helper and optional parameters

This just bit me, and I'm wondering why is this necessary:

  apply_helpers = (ctx) ->
    for name, helper of helpers
      do (name, helper) ->
        if typeof helper is 'function'
          ctx[name] = (args...) ->
            args.push ctx  # ???
            helper.apply ctx, args
        else
          ctx[name] = helper
    ctx

Why do we need to add the context to the arguments? It's already available as, you know, the context.

It's very difficult to use optional arguments with this, and it's not documented.

Content negotiation

From my understanding it's impossible to do via connect/express middleware, and it could be nice addition to zappa.
Say,

@get '/': ->
  @render index: {foo: 'bar'}

And if request has header Accept-type: application/json, server will respond with JSON {"foo":"bar"} instead of view index rendered with {foo:"bar"}
Will it be accepted into upstream? If yes, I can do that

Broadcast Test Fails

I tried to fix this myself, but nothing seems to work:

sockets.coffee: server broadcasts
----------------------------------------
✖ reached1 (not reached)
✖ reached2 (not reached)
✖ data1 (not reached)
✖ data2 (not reached)

Using io.sockets.send works, but it's not really a broadcast (because the sender will receive the message as well).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.