Giter Club home page Giter Club logo

examples's Introduction

Koa Examples

A repository containing small examples to illustrate the use of Koa for creating web applications and other HTTP servers.

Running tests

npm test
npm run lint

Included Examples

Example Repositories

  • coko - A minimal convention over configuration framework/boilerplate for Koa 2.
  • kails - A Web App like Rails build with Koa v2, Webpack and Postgres
  • muffin - A content management system build on top of Koa v2
  • links - experimental content sharing and collaboration platform
  • component-crawler - crawl users and organizations for repositories with component.jsons
  • bigpipe - Facebook's BigPipe implementation in koa and component
  • webcam-mjpeg-stream - stream JPEG snapshots from your Mac
  • cnpmjs.org - Private npm registry and web for Enterprise, base on koa, MySQL and Simple Store Service
  • blog-mongo - the blog example from this repo, but using a MongoDb database, and tests
  • koa-rest - A simple app to demo REST API
  • koajs-rest-skeleton - A simple Koa REST Skeleton Application
  • koa-bookshelf - Koa example with CRUD, using MongoDB and Heroku comptability
  • todo - A todo example written in koa and react
  • koa-skeleton - A simple made-to-be-forked Koa app that uses Postgres and deploys to Heroku.
  • nodejs-docs-samples - An example Koa app and tutorial for deploying to Google App Engine
  • koa-passport-mongoose-graphql - Koa 2 starterkit using mongoose, graphql setup, and authentication with passport
  • hacknical - A website for github user to make a better resume, based on Koa v2, redis and mongoose.
  • koa-vue-notes-api - A fleshed-out SPA using Koa 2.3 on the backend and Vue 2.4 on the frontend. Includes fully featured user-authentication components, CRUD actions for the user's notes, and async/await.
  • koa-typescript-node - Template for building nodejs and typescript services. Features: MySql, Migrations, Docker, Unit & Integration Tests, JWT authentication, authorization, graceful shutdown, Prettier.

Boilerplates

Yeoman Generators

  • koa-rest - RESTful API scaffolder with subgenerator
  • koa - Web Application scaffolder
  • k - Web Application scaffolder with Chinese README

Articles

examples's People

Contributors

amilajack avatar bananaappletw avatar bhaskarmelkani avatar danneu avatar dead-horse avatar denizozger avatar embbnux avatar ericdouglas avatar hafffe avatar hemanth avatar jedwood avatar jmdobry avatar joeyguerra avatar johndatserakis avatar jonathanong avatar k-j-kleist avatar kevinrambaud avatar kitak avatar leo avatar marcusoftnet avatar mhbseal avatar mjhea0 avatar nickmccurdy avatar septatrix avatar talento90 avatar timaschew avatar tj avatar vorandrew avatar yosssi avatar zachary95 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  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

examples's Issues

multipart/app.js - files is accessed directly from ctx.request as opposed to ctx.request.body

I know the version of koa used in the examples differs from the version I'm using following along with the examples (2.2.0 vs. 2.5.2), but wanted to raise a fundamental difference in the ctx object for extracting files from the request:

app.js in the examples has the following:

const files = ctx.request.body.files || {};

In version 2.5.2, this has to be set as follows:

const files = ctx.request.files || {};

Pretty sure it's a difference between versions, but figured I'd raise the issue in the event that someone else has troubles.

Javascript qstn

[2:54 pm, 03/08/2021] 🍫🍫: 1. Given values on the next page, write a function that returns an array of strings in the
following format
["Norah | AAA-6818 | 564.67","Norah | AAA-4671 | 138971.19"]
2. Execute your function and output the results as an array in console log for the following
scenarios:
A) filtered by Norah with all account types (ROT, IRA, AAA)
B) filtered by account type sorted by balance ascending
C) filtered by Alyx with IRA account type; sorted by balance descending
D) filtered by All users; sorted by balance ascending
users = [
{
id: "1",
name: "Norah"
},
{
id: "2",
name: "Alyx"
}
];
accounts = [
{
account: "IRA-4679",
user: "1",
balance: "5175.36"
},
{
account: "AAA-3571",
user: "1",
balance: "3896342.08"
},
{
account: "AAA-4671",
user: "1",
balance: "138971.19"
},
{
account: "ROT-1687",
user: "2",
balance: "2686.00"
},
{
account: "AAA-7894",
user: "2",
balance: "68761.32"
},
{
account: "IRA-6818",
user: "2",
balance: "564.67"
},
{
account: "IRA-6819",
user: "2",
balance: "4564.67"
}
};

readme.md or comments?

i think most people are going to just view this on github vs. actually cloning it, so i think we should move most of the non-technical and philosophical explanations to a readme in each directory. opinions?

can't run test.js

I'v installed the dependence, but , I can't run the test.js file like this:

node .\base-auth\test.js

It shows ReferenceError: describe is not defined.
can they be runing successfully in your computer?

I use vscode 1.17.1
Os: windows
node is the latest version 8.6.0

Koa <-> Express integration

While the Koa docs specifically say that setting ctx.respond to false is not a supported pattern, it is necessary for embedding a Koa application into a large Express application -- the use case is incrementally moving routes from Express/Connect style to Koa. I'm curious if you're open to adding an example here of how to do that, because it can be a little tricky and there are several pitfalls. As a reference example I put together this repo: https://github.com/bttmly/koa-within-express

But I think it could be useful here for others looking for an Express to Koa migration path!

Internal Server Error for stream-server-side-events example

Using master from koajs/examples with node v0.12.0 to run the stream-server-side-events example program, I had a couple problems:

  1. I had to add if (!module.parent) app.listen(3000); as the final line of app.js

  2. I got the following error when I connected to http://localhost:3000

    richs-mbp-10715:stream-server-side-events richb$ node --harmony app.js
    
    RangeError: msecs must be a non-negative finite number
        at Object.exports.enroll (timers.js:160:11)
        at Socket.setTimeout (net.js:329:12)
        at IncomingMessage.setTimeout (_http_incoming.js:89:15)
        at Object.<anonymous> (/Users/richb/github/KoaJSExamples/stream-server-side-events/app.js:9:12)
        at GeneratorFunctionPrototype.next (native)
        at Object.respond (/Users/richb/node_modules/koa/lib/application.js:180:10)
        at GeneratorFunctionPrototype.next (native)
        at Object.<anonymous> (/Users/richb/node_modules/koa/node_modules/koa-compose/index.js:29:12)
        at GeneratorFunctionPrototype.next (native)
        at onFulfilled (/Users/richb/node_modules/co/index.js:61:19)
    
    ^C
    
  3. If I comment out the line setTimeout(Infinity) line, I get the following when I hit the server:

    richs-mbp-10715:stream-server-side-events richb$ node --harmony app.js 
    events.js:85
      throw er; // Unhandled 'error' event
            ^
    TypeError: Invalid non-string/buffer chunk
    at chunkInvalid (_stream_readable.js:384:10)
    at readableAddChunk (_stream_readable.js:140:12)
    at Subscription.Readable.push (_stream_readable.js:126:10)
    at Subscription._read (/Users/richb/github/KoaJSExamples/stream-server-side-events/db.js:30:30)
    at Subscription.Readable.read (_stream_readable.js:341:10)
    at resume_ (_stream_readable.js:725:12)
    at _stream_readable.js:717:7
    at process._tickCallback (node.js:355:11)
    
    

stream-view example

in this example. it can only handle one connection at once. The other connections are waitting for the previous one finish up to start streaming process

base-auth/app.js

app.use(function* (next){
  try {
    yield* next;
  } catch (err) {
    if (401 == err.status) {
      this.status = 401;
      this.body = 'cant haz that';
    } else {
      throw err;
    }
  }
});

==>

app.use(function *(next){
  try {
    yield next;
  } catch (err) {
    if (401 == err.status) {
      this.status = 401;
      this.set('WWW-Authenticate', 'Basic');
      this.body = 'cant haz that';
    } else {
      throw err;
    }
  }
});

Some question about "404" example

I tried the 404 example , but I found some problems

I tried to make some requests with different custom headers(text/plain and application/json), but the I found that the responses were not what I expected:

~ http --print=Hhb localhost:3000 Content-Type:text/html
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: text/html
Host: localhost:3000
User-Agent: HTTPie/0.9.9

HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 21
Content-Type: text/html; charset=utf-8
Date: Wed, 03 May 2017 16:48:50 GMT

<p>Page Not Found</p>~ http --print=Hhb localhost:3000 Content-Type:application/json
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json
Host: localhost:3000
User-Agent: HTTPie/0.9.9

HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 21
Content-Type: text/html; charset=utf-8
Date: Wed, 03 May 2017 16:50:05 GMT

<p>Page Not Found</p>~ http --print=Hhb localhost:3000 Content-Type:multipart/form-data
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: multipart/form-data
Host: localhost:3000
User-Agent: HTTPie/0.9.9

HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 21
Content-Type: text/html; charset=utf-8
Date: Wed, 03 May 2017 16:50:35 GMT

<p>Page Not Found</p>

No matter how I set up what kind of Content-Type,The results are always same.

Is this a bug or my use is not correct?

blog Error: Invalid cache option true found

Hi,
I cloned the whole repo and ran npm install, then nav into blog/ ran 'node index.js', and got this error. Can you help with it? thank you. 😄

I'm using node v5.4.0 and linuxmint 3.16.0-38-generic.

Error: Invalid cache option true found. Expected "memory" or { get: function (key) { ... }, set: function (key, value) { ... } }.
      at validateOptions (/home/sabrina/sa/koa-examples/node_modules/swig/lib/swig.js:113:15)

rolling app updates

I hope this makes sense but I am trying to see how I will be able to update my application with koa with no restart.

basically, all started request should keep flowing as they began ; all new request should flow to the new version of the app.

in pseudo code it would be something like

var rolling = [ myapp ]
var app = koa();
app.use(function *() {
    var m = compose(rolling[0])
    return yield m.call(this, next);
});

... somewhere an event does a
rolling.unshift(newapp);

now if I have a koa-livecount middleware like

function livecounter() {

  var count = 0;
  return function livecount*(next) {
    count +=1;
    yield next;
    count -=1;
  }

}

with

myapp.use(livecounter());

I could know when myapp has finished handling requests.
(is this really correct when throw is used somewhere below ? is there a way to know when there are zero processing requests downstream for an app or a middleware ?)

when i know that myapp is not used anymore I can pop it out of the rolling array.

do you think something like this could work and could we try to setup an example for this ?

Add websocket example

Adding an example for how to do websockets would be grand, I'll PR one once I figure it out myself 😅

Error example, how to handle unthrown 404.

The error example only details how to handle this.throw and throw new. Where as the koajs application *respond(next) generator handles 404 by

// status body
var status = this.status = this.status || 404;
...
if (null == body) {
  this.type = 'text';
  body = http.STATUS_CODES[status];
}

I would need to use a second generator to repeat similar logic to the *respond(next) generator to enforce json as well. Any suggestions how to handle this elegantly / use the same try / catch generator as per the example?

vhost example with koa-compose 3.0.0

If I understand well, the vhost example no longer works with version 3.0.0 of koa-compose.

Could it be updated?

I take it koa-compose 3.0.0 cannot be used with Koa 1.x.x.

Mount Koajs app on top of Express that runs a server

I have an Express app that already starts its own http server. How can I mount a koa app on top of this existing server, so that it shares the same port? Similar to how you would mount subapps in Express

Would I include the koa app as an Express middlware? Do I still use app.callback() for that?

Properties not working for ctx.throw

Hello, I am trying to use the properties parameter with ctx.throw but I do not see the object added anywhere in the response. For example, if part of a request message is missing, I want to do something like the following:

if (!username) {
    return ctx.throw(400, 'Invalid request message', {
        validationErrors: {
            username: 'Username cannot be null',
        },
    });
}

When I try to do a console.log of the response, I see the status and message set properly but I do not see the validationErrors object in the response. Any suggestions on this are appreciated.

update examples to koa@2

While studying koajs capabilities i made some REST API by using latest koa.
The question are examples, in this repo, should consist of next version yet or until official release only koa1?

About my code https://github.com/DoumanAsh/lazy-http-can
This repo consist of simple REST service that allows you to test HTTP requests.
There are several things:

File Upload issue

Hi,

I'm trying to upload files using the code from example. But it's not working.

In the controller I wrote the code

var parse = require('co-busboy');
var fs = require('fs');
var path = require('path');

var parts = parse(this);
var part;

while (part = yield parts) {
    var stream = fs.createWriteStream('/tmp/' + part.filename);
    part.pipe(stream);
    console.log('uploading %s -> %s', part.filename, stream.path);
}

But when I upload images in the console I only get new uploading location. But on new location images are not saving.

Any Solution?

Thanks in Advance,
Nixon

It's not about stream

try to log every push on server - you'll see than on a client there is not a stream - there is long waiting for whole result as usual
In my samples the first push occurs in 2 ms but on the client TTFB is equal sum of times in the request - so there is no real stream unfortunately

Update koa-router and swig

Both packages are currently unmaintained.

Koa-router has already been forked by us and is available as @koa/router.
Swig has been forked too and undergoes some further development as swig-templates.

These two forks aren't under to much development either and more or less stale but using @koa/router gives us a bit more control and swig-templates already fixed some bugs and has more up-to-date dependencies (which npm audit will tell you).
I haven't bothered looking into the other packages but these two I think should get updated...

compose: undefined in logger

there is a "undefined" when I run the compose/app.js
undefined / - 6
undefined / - 1
undefined /aaaa - 0

I think that the code 'this' will be modified to 'ctx' in the 'logger()' function.

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.