Giter VIP home page Giter VIP logo

helapkg / hela Goto Github PK

View Code? Open in Web Editor NEW
331.0 8.0 41.0 2.69 MB

:icecream: Powerful software development experience and management. Enhancing @tc39 JS, @denoland and @nodejs, because we need a bit of magic. :sparkles: You can think of it as Cargo for the JavaScript ecosystem.

License: Mozilla Public License 2.0

JavaScript 100.00%
tunnckocorehq hela hela3 task-runner development-environment shareable-configs platform ecosystem hela-ecosystem execa

hela's Introduction

hela

🍦 Powerful software development experience and management. ✨

hela's People

Contributors

carlitux avatar creeperyang avatar dan-dr avatar greenkeeperio-bot avatar manuscriptmastr avatar pepkin88 avatar poppinlp avatar renovate-bot avatar renovate[bot] avatar sedenardi avatar tunnckocore avatar wisdom-yzh 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

hela's Issues

Problems with koa-better-router?

Hi,

Awesome middleware you made here!

I'm starting with koa and your middlewares seem pretty great so i'm using koa-better-router & koa-better-body together.

However things are not working as expected. I'm

import koa from 'koa';
import body from 'koa-better-body';
import Router from 'koa-rest-router';
import convert from 'koa-convert';

const app = new koa();

apiRouter.resource('users', {
    index: [
        (ctx, next) => {
            ctx.body = "list users!\n";
            return next(); 
        },
        function *(next) {
            this.body = `${this.body} and blah blah..`;
            yield next;
        }
    ],

    recent: (ctx, next) => { ctx.body = "Newly created user!\n"; return next(); },

    create: (ctx, next) => { ctx.body = "Create users!\n"; return next(); },

    edit: (ctx, next) => { ctx.body = "Edit user view!\n"; return next(); },

    update: [body,
        (ctx, next) => {
            ctx.body = "create users!\n";
            return next(); 
        },

        function *(next) {
            this.body = `And incoming data is ...`;
            this.body = `body from req ${this.body} ${this.request.fields}`;
            yield next;
        }
    ],

    remove: (ctx, next) => { ctx.body = "remove users!\n"; return next(); }
}, {map: {'new': 'recent'}, methods: {'put': 'post'}});

const basic = new Router(); //- For routes not beginning with /api/v1
basic.extend(apiRouter);

app.use(convert(body())); //- did this out of desperation
app.use(apiRouter.middleware());
app.use(basic.middleware());

This code is from chunks of your koa-better-router examples and problem comes when i use update which is using body.

If i include "body" as the beginning arg in update and post something to /users/1 i get Not Found and nothing gets run cause update controller wasn't the one called (no controller was).

    update: [body,
        (ctx, next) => {
            ctx.body = "create users!\n";
            return next(); 
        },

        function *(next) {
            this.body = `And incoming data is ...`;
            this.body = `body from req ${this.body} ${this.request.fields}`;
            yield next;
        }
    ],

If i remove the "body" from the update and call this.request.fields i get error.
Update code when i remove body

    update: [
        (ctx, next) => {
            debugger;
            ctx.body = "create users!\n";
            return next(); 
        },

        function *(next) {
            this.body = `body from req ${this.request.fields}`;
            console.log(this.request);
            yield next;
        }
    ],

Error Msg when i remove body

  TypeError: Cannot convert object to primitive value
      at Object._callee2$ (/home/users/Projects/koa/test-project1/dist/index.js:70:54)
      at tryCatch (/home/users/Projects/koa/test-project1/node_modules/regenerator-runtime/runtime.js:64:40)
      at Generator.invoke [as _invoke] (/home/users/Projects/koa/test-project1/node_modules/regenerator-runtime/runtime.js:355:22)
      at Generator.prototype.(anonymous function) [as next] (/home/users/Projects/koa/test-project1/node_modules/regenerator-runtime/runtime.js:116:21)
      at onFulfilled (/home/users/Projects/koa/test-project1/node_modules/co/index.js:65:19)
      at /home/users/Projects/koa/test-project1/node_modules/co/index.js:54:5
      at Object.co (/home/users/Projects/koa/test-project1/node_modules/co/index.js:50:10)
      at converted (/home/users/Projects/koa/test-project1/node_modules/koa-convert/index.js:17:15)
      at dispatch (/home/users/Projects/koa/test-project1/node_modules/koa-compose/index.js:44:32)
      at next (/home/users/Projects/koa/test-project1/node_modules/koa-compose/index.js:45:18)

Please help.

How to store different type files in different dir?

For example:

//ajax's url
url: '/upload/images'

And I want to store it in uploads/images dir.

Another one:

//ajax's url
url: '/upload/films'

And I want to store it in uploads/films dir.

Now I used it this way,and whatever type it is,It will store in uploads dir.

app.use(convert(body({
       encoding: 'utf-8',
       uploadDir: path.join(__dirname, 'uploads'),
       keepExtensions: true
    })))

How can I do to store different type files in different dir?

Support qs syntax?

It'd be nice if the input names supported qs syntax so <input name="foo.bar" value="quz"> and <input name="foo[bar]" value="quz> would set

this.request.foo.bar = quz

This is supported in the regular body-parser.

extended the extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.

koa-better-body doesn't correctly parse ampersands in multipart form

I'm using koa-better-body as middleware for a backend-only web application. When I submit a multipart form with a text description that has an ampersand (i.e. "Love this B&W shot"), the browser correctly sends the payload, but better-body turns the part after the ampersand into a new field. Think the error is happening here:

https://github.com/tunnckoCore/koa-better-body/blob/master/utils.js#L208-L214

Does it look that's where the problem is? I'd be happy to submit a pull request if someone isn't already addressing this.

Example:

Chrome sends server:

------WebKitFormBoundaryJyFdnMnS1k2XUhGH
Content-Disposition: form-data; name="image"; filename="IMG_2194.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryJyFdnMnS1k2XUhGH
Content-Disposition: form-data; name="description"

I love me some &sandisgood
------WebKitFormBoundaryJyFdnMnS1k2XUhGH
Content-Disposition: form-data; name="type"

Cortado

ctx.request.fields prints out:

{ description: 'I love me some ',
  sandisgood: '',
  type: 'Cortado',
  image: 
   [ File {...} ] }

Parsing form and `qs` syntax while form is multipart/form-data

Currently if the form is multipart it is handled by the multipart parser, but fields also comes from that parser. So we should use detection if formidable give you some fields, so you one more parse - this.request.urlencoded so it will be able to handle qs syntax.

For example

<form action="/" method="post" enctype="multipart/form-data">
    <input type="file" name="img" multiple="multiple">
    <input type="input" name="foo">
    <input type="input" name="bar">
    <input type="input" name="baz[qux][aa]">
    <input type="input" name="baz[qux][bb]">
    <button>Upload</button>
</form>

expected results are

  • this.request.fields is always an object
  • this.request.files always to be an array, even if type="file" not accepts multiple files - for consistency, not make sense to be object as it is currently in v1.x and v2.x
  • this.request.fields also holds the files in the named field, so:
    • this.request.fields.img is array, same as this.request.files
  • this.request.fields.foo - value of foo field
  • this.request.fields.bar - value of bar field
  • this.request.fields.baz to be an object if qs module is used/passed to opts.querystring

upcoming v2

see the milestone (click more) and the issues for v2

It seems something was broken between last commits and the git back to the latest stable passing commit not have success.

Cant parse array data properly (send via `FromData`)

Data will be like this:

Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryUzoXapxqkoPvr8T2

...

------WebKitFormBoundaryUzoXapxqkoPvr8T2
Content-Disposition: form-data; name="tags[]"

569899aad67fa76e5ad3d663
------WebKitFormBoundaryUzoXapxqkoPvr8T2
Content-Disposition: form-data; name="tags[]"

569899aad67fa76e5ad3d664

...

And better-body only get one item of tags[], I mean the parsed data will be like this:

fields: {
   'tags[]': '569899aad67fa76e5ad3d664'
}

Maybe the lib(formidable) just overwrite the tags[], and cant handle array notation properly.

How i can manually convert to buffer?

If i pass buffer: true, I have no problem, it works.

The problem is that i don't want all requests to be a buffer, so i removed the property and instead i'm doing Buffer.from(ctx.request.body) but i'm getting a different buffer instead.

Any idea why?

Koa v2

The README.md file shows:

Full-featured koa body parser! Support parsing text, buffer, json, json patch, json api, csp-report, multipart, form and urlencoded bodies. Works for koa@1, koa@2 and will work for koa@3.

I was a bit confused by this message. Is there a koa@3, and does this lib really work for koa@2?
In my case, I had to use koa-convert to get this working for koa-2 and koa-router

how to set upload dir?

with koa-body, we can set the upload dir like this:
`var app = require('koa')(),
koaBody = require('koa-body');

app.use(koaBody({formidable:{uploadDir: __dirname}}));`

but with this middleware, it's not working. it upload to '/var/folders/....'
how can i set the upload dir

Error on POST requests

  TypeError: Cannot read property 'fields' of undefined
      at Object.koaBody (./node_modules/koa-better-body/index.js:90:61)
      at GeneratorFunctionPrototype.next (native)
      at next (./node_modules/co/index.js:74:21)
      at Object.<anonymous> (./node_modules/co/index.js:45:5)
      at next (./node_modules/co/index.js:90:21)
      at Object.<anonymous> (./node_modules/co/index.js:45:5)
      at next (./node_modules/co/index.js:90:21)
      at Object.<anonymous> (./node_modules/co/index.js:45:5)
      at next (./node_modules/co/index.js:90:21)
      at Object.<anonymous> (./node_modules/co/index.js:45:5)

Why is koa-better-body writing to ctx.body

I'm confused: why is koa-better-body setting the request parameters on ctx.body (which is an alias to the response body, according to the docs).

As a result, whenever my middleware does not explicitly set the body, then koa-better-body does it for me. See:

var Koa = require('koa');
var body = require('koa-better-body')
var convert = require('koa-convert')
var app = new Koa();
app.use(convert(body()))
app.listen(4290, function () {
  console.log('Koa server start listening on port 4290')
  console.log('curl -i http://localhost:4290/ -F "key=val"')//should return nothing
})

When i try to upload multiple files

I try to upload multiple files with this code..
<input type="file" name="files" multiple="true">

It's incorrect format, I think it should be array under files field.
screen shot 2559-08-12 at 11 46 45 pm

Thanks

Give user the way to register `formidable` events and so they can deal with file uploading

Sometimes we need to rename file(set file path) dynamically, so it's important to give a way to interact with formidable. (Current formidable options are not enough.)

Demo:

// upload Blob
------WebKitFormBoundaryi8ZhzSYa1jK76hJC
Content-Disposition: form-data; name="tags"

56a1f2c06dfc44c4570a46cb,56a1f2c06dfc44c4570a46cc
------WebKitFormBoundaryi8ZhzSYa1jK76hJC
Content-Disposition: form-data; name="headImg"; filename="blob"
Content-Type: image/jpeg


------WebKitFormBoundaryi8ZhzSYa1jK76hJC--

Here I have to register fileBegin event to add extension to filename:

form.on('fileBegin', function(name, file) {
    file.name = xxxx; // add ext to file.name, retrive ext from file.type
    file.path = xxxx; // add ext
});

v3: hybrid, make it accept `app`

for v2.x. Something like

var koa = require('koa')
var body = require('koa-better-body')

var app = koa()
app.use(body.middleware(options))

Or you will be able to use it like koa-body-parsers

var koa = require('koa')
var Body = require('koa-better-body').KoaBetterBody
var app = koa()
new Body(app)

app.use(function * () {
  this.body = yield this.request.multipart(options)
  // this.body = yield this.request.json(options)
  // etc
})

something like that.. it's not clear enough in my mind.

Issue integrating this with other middleware such as koa-passport

after much research the root of the issue seems to be that passport-local looks for fields directly of of the koa body object i.e. this.request.body

but because this plugin sets the fields on this.request.body.fields, passport-local thinks there are none and authentication fails.

would it be possible to set the fields on the body itself i.e. this.request.body = form.parse...or json.parse

and to avoid the naming conflict of the files set that on the request object itself?

I have noticed that most other body parsers set the fields in the body itself.

Cannot set property 'files'

TypeError: Cannot set property 'files' of undefined
at handleRequest .../node_modules/koa-better-body/index.js:125:23)

It can be changed to better

returns = returns || {};
returns[filesKey] = cache.files;

Conflict on ctx.querystring of koa2

In koa2, ctx.querystring is equal to url search string.
for example, when i make a request such as:
curl -X POST 'http://localhost:3000/a/b?c=1&d=2' -d 'e=3&f=4'
ctx.querystring will be equal to 'c=1&d=2' and it is a string, not an object with method parse.
at last, module koa-body-parsers will throw error as below:
this.ctx.throw(400, 'invalid urlencoded received')

so ctx.querystring below may be removed if koa-version is 2.0?
ctx.app.querystring = opts.querystring ||
opts.qs || // alias
ctx.app && ctx.app.querystring ||
ctx.app && ctx.app.qs || // alias
ctx.querystring ||
ctx.qs // alias

A few ideas: options.extendTypes.custom, options.handler, split buffer thingy?

Get an ideas.

split buffer thingy

Currently (in v2.0):

  • if you wanna buffer body, you should pass options.buffer: true and trick the things through options.extendTypes.text (because that's the only way to use the this.request.buffer parser to parse buffers). you will receive it in this.request.body
  • If you wanna limit the buffer size you should pass options.textLimit or options.bufferLimit

I'm asking myself, isn't it will be better if there's separate if for options.extendTypes.buffer and try to parse it separate from text? So i came to the next idea for extendTypes.custom

options.extendTypes.custom and options.handler

So, to be able hack the things legally. Meaning if you wanna parse foo/bar-x type, for instance, you will pass that type to options.extendTypes.custom: ['foo/bar-x'], then options.handler.call(ctx, ctx, options, next) will be called.

related: #22 and #31

This will give you the freedom and ability to do whatever you want:

  1. access the this context (ctx)
  2. access the original options (options)
  3. to use all of the parsers - ctx.request.json, ctx.request.urlencoded, ctx.request.multipart, ctx.request.text and ctx.request.buffer
  4. and what your mind can think

Cann‘t parse json

My code

const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const url = require('url');
const util = require('util');
const Koa = require('koa');
const enforceHttps = require('koa-sslify');
const favicon = require('koa-favicon');
const serve = require('koa-static');
const logger = require('koa-logger');
const bodyParser = require('koa-better-body');
const session = require('koa-session-minimal');
const redisStore = require('koa-redis');
const handleError = require('koa-handle-error');
const render = require('koa-ejs');

const app = new Koa();
render(app, {
    root: path.join(__dirname, 'views'),
    layout: false,
    viewExt: 'ejs',
    cache: false,
    debug: true
});
app.use(logger());
app.use(enforceHttps());
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(serve(__dirname + '/public'));
app.use(bodyParser());
app.use(async (ctx, next) => {
    return next();
});

I set breakpoint behind app.use(bodyParser());, ctx.request.fields is still null.

pre v2.0 - tests, docs, recipes

tests

  • for koajs/koa-body#15 (multiple fields)
  • for #26 (array data)
  • for options.onerror
  • may need to separate them to test/ dir

docs

  • document index.js
  • document utils.js
  • rich readme

recipes (post-v2)

  • parsing xml body
  • rich examples
  • usage with other middlewares: koa-router, koa-route, koa-resource, more
  • koa@2 way
  • jsonStrict and non-strict
  • extendTypes
  • onerror
  • multipart: custom files and fields names
  • formidable.IncomingForm instance: events handling

Plans for koa@2 support by default, if you don't want to use koa-convert. Maybe v2.2 or v3.

todo test: when fieldsKey/filesKey not string

if (typeof opts.fieldsKey !== 'string') {
  copy = copy.fields;
}

@pepkin88 also need to check if filesKey is string.. xD

Mainly, the idea behind this checks and the false concept was, if option is set to false, then pass the body, directly to the this.request object (as you mention this.request.files)

Unable to access files when fieldsKey is set to false

In the code is a fragment:

if (typeof opts.fieldsKey !== 'string') {
  copy = copy.fields
} else {

which means that information about files is deleted. What was the reasoning behind this? Earlier there was an option filesKey, why was it removed? Could this new behavior be reverted, so that it is possible to access uploaded files?

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.