Coder Social home page Coder Social logo

adonisjs / core Goto Github PK

View Code? Open in Web Editor NEW
15.4K 222.0 614.0 5.69 MB

AdonisJS is a TypeScript-first web framework for building web apps and API servers. It comes with support for testing, modern tooling, an ecosystem of official packages, and more.

Home Page: https://adonisjs.com

License: MIT License

TypeScript 99.79% JavaScript 0.21%
nodejs nodejs-framework typescript typescript-framework framework web-framework core mvc-framework

core's Introduction

@adonisjs/core



Fullstack MVC framework for Node.js

AdonisJs is a fullstack Web framework with focus on ergonomics and speed . It takes care of much of the Web development hassles, offering you a clean and stable API to build Web apps and micro services.


gh-workflow-image npm-image license-image

Built with ❀︎ by Harminder Virk

core's People

Contributors

allanfreitas avatar ammezie avatar arabbani avatar atinux avatar bartduisters avatar blackwidow-sudo avatar chukitow avatar croquetmickael avatar daltonvarao avatar dependabot-preview[bot] avatar dependabot[bot] avatar femaffezzolli avatar goschevski avatar grantcopley avatar grantholle avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jakgajtk avatar julien-r44 avatar mastito03 avatar mcsneaky avatar moltar avatar mul14 avatar ntvsx193 avatar r15ch13 avatar romainlanz avatar targos avatar thetutlage avatar webdevian avatar yariksav 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

core's Issues

use socket on adonis

hi ...
how i can integrate socket.io with adonis...
can show me a very simple demo ...

Integrate knex.js seed

It would be really nice to have a functionality to insert test or default data, after running database migrations. There is already an CLI as in knex.js docs outlined.

Seed files allow you to populate your database with test or seed data independent of your migration files.

Are there any plans to integrate that feature? What do you think about it?

Is there any built-in pagination for models?

Hello. I've read the documentation on site, but can't find anything about that. There is offset and limit functions in queries doc, plus count function in Aggregates section. But there is nothing like this for models. May be I've missed something.

Style Guide

Trailing Whitespace

In the .editorconfig you have put an option to trim trainling whitespace on save.

root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

But there's a lot of trailing whitespace on the code . Before someone send a PR with a lot of change in the code (cause of the trim) it would be great to remove them with something like https://github.com/zhengjia/rstrip.

Tab VS Space

There's also in the .editorconfig an option to use space instead of tab.
But in some parat of the code you have tab. It should change.

Comments

Are you using a convention to comment your code? Some have the meta tag @description and some has not.

Asset Pipeline

Hi all, I'd be interested in helping out with a Gulp based asset pipeline. My initial thoughts are to have Less, Stylus & Sass support but default to Sass due to popularity (not my first choice btw - but makes sense). I could also setup BrowserSync and Browserify with an initial client side JS setup. I haven't dug into ES6 just yet, so would probably need a little help in that regard. I also recommend Bootstrap 4 (though I prefer Foundation 6) again due to popularity and would mean users can prototype super-quick. Not sure how to handle static assets (such as images etc.) unless we develop locally assuming a production environment.
I'd appreciate any thoughts on the above - thanks.

heroku deployment

Hi, I did a clean deploy to heroku and looking at the logs, it was looking for .env on the app/ directory rather than the root directory, is this normal?

Are there any configurations necessary to successfully deploy an adonisjs app to heroku?

how to change session path

router

Route.post('/admin/login', 'AdminController.login');

code

  *login(request, response) {
    const method = request.request.method;
      const postData = request.post()
      if (postData.account == "[email protected]" && postData.password == "123456") {
        yield request.session.put(postData)
      } else {
        return "η”¨ζˆ·εζˆ–ε―†η ι”™θ――"
      }
  }

image

the path is /admin,so how can i change it to /?

Preprocessor support

Hypothetically speaking, where would one add in preprocessor support in the application? Having gotten the UI/UX team invested in sass, it's going to be one hell of a struggle to rip it away from them. In previous applications, we used gulp to run tasks which produces artifacts in the static route, not sure how to go about in adonis.

can i use adoinsjs now?

First.this is a awesome framework. I really like it. After looking the documentation, I think this framework like Larael in some ways. Because it's a brand new framewor, I am not sure I can use it in production now! Can I?

.env file add possibility to bind to an host

Currently we can only bind to a port
APP_PORT=80

It would be convenient to define a host too
APP_HOST=127.0.0.1

That will be handled by server.start(host, port)

/**
 * @function start
 * @description start http server on a given port
 * @param  {Number} port
 * @public
 */
Server.prototype.start = function (port) {
  this.Logger.info('serving app on port %s', port)
  this.serverInstance.listen(port)
}

Syntax migration - knex

Below is my code for create a table

  up () {
    this.dropIfExists('skills_projects')
    this.create('skills_projects', (table) => {
        table.increments('id').first()
table.integer('id_project').references('id').inTable('projects').onUpdate('CURRENT_TIMESTAMP').onDelete('CASCADE')
        table.integer('id_skill').references('id').inTable('skills').onUpdate('CURRENT_TIMESTAMP').onDelete('CASCADE')
    })
  }

error:

alter table "skills_projects" add constraint skills_projects_id_project_foreign foreign key ("id_project") references "projects" ("id") on update CURRENT_TIMESTAMP on delete CASCADE - syntax error at or near "CURRENT_TIMESTAMP"

So what is correct way to do it?

Middleware issue

code in kernel.js

const namedMiddlewares = {
  'auth':'App/Http/Middleware/Authentication'

}

router

Route
  .get('/admin/dashboard','AdminController.dashboard')
  .middleware(['auth'])

error

ReferenceError: namedMiddlewares is not defined
    at Object.<anonymous> (/Users/wangtieshou/Project/tenread-weekly/app/Http/kernel.js:42:18)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.Loader.require (/Users/wangtieshou/Project/tenread-weekly/node_modules/adonis-fold/src/Loader/index.js:32:12)
    at Object.Loader._makeDump (/Users/wangtieshou/Project/tenread-weekly/node_modules/adonis-fold/src/Loader/index.js:155:17)
    at Object.Loader.resolveUsingType (/Users/wangtieshou/Project/tenread-weekly/node_modules/adonis-fold/src/Loader/index.js:93:27)
    at Ioc.use (/Users/wangtieshou/Project/tenread-weekly/node_modules/adonis-fold/src/Ioc/index.js:227:30)
    at /Users/wangtieshou/Project/tenread-weekly/bootstrap/http.js:69:5
    at process._tickCallback (node.js:377:9)
    at Function.Module.runMain (module.js:459:11)
    at startup (node.js:136:18)
    at node.js:972:3

auto-loader includes **every** file when using a directory path which causes parsing errors in specific cases

As example: when running migration tasks they break when having a non regular js-file in the migration directory.

In my specific case it was a .DS_Store file, with ace message:

$ ./ace migration:run
Unexpected token .

The auto-loader includes the whole directory and has, as far as I could evaluate, no possibility to use globs pattern. This may cause a lot of problems when you want to include other files in the directories as well - for instance markdown files for documentation.

Beside that, ace stops execution on error but the process isn't stopped. It should exit with status code 1 instead, right?

Regards
Philipp

problem with service provider inject

hi ..
i try add socket.io to my project whit the help your post ... and this work fine
but i have new problem ... when i want use my provider in socket.js the inject library not load and return undefined for injected library to service provider ...
but i not have problem when use provider in controllers ..

plz help again ...:)

Installation Documentation

Hi, just thought I'd point out that the documentation differs a little from an actual installation.
image
I instead ran node ace server:start - might also be worth pointing out that to kill the process, users should run node ace server:stop.

Thanks in advance.

How to select hidden Lucid fields?

I have a model, let's say it's a User model.

In most cases I don't want the password to be returned, so I add it to hidden fields. How can I include a hidden field where I do need it, for example when authenticating a user logging in?

yield User.select('id', 'username', 'password').where('username', credentials.username).fetch()

seems to fail here.

Gitter channel

Hey,

I read there that you have a Slack Channel? Can you make it public or maybe create a Gitter chat room to discuss about the project? It would be better than create issues.

Websocket support

Hi all, I'd be very interested to see how we could tackle websocket support as there are many possible options.
For example, we could recommend that such functionality should be offloaded to Pusher or we could document how to use a socket.io cluster. If you're to use Websocks, once your app gets big you'll want to account for a solid scaling setup (Redis etc.). Also, see Sailsjs for example who make it very easy to utilise Websocks on the client. Happy to discuss & assist wherever I can, thanks.

Configure HoundCI

HoundCI don't very like ES6 for the moment.

Is it possible to configure it or remove it?

Examples

LTS

What do you think about LTS? Will you release LTS version?

Adonis/Src/Logger is gone

In Version 1.* we were able to use const Logger = use('Adonis/Src/Logger');. This seems to be gone now. Is this Provider not supported anymore or just missing?

Nested route groups

Route groups are very useful and help a lot. How about to make them nesting?
Some sort of Rails sugar.

Route.group('admin',function () {

  // Users
  Route.group('users',function () {

    Route.get('/','UsersController.index');

  }).prefix('/users').close()

}).prefix('/manage').close()

Adonis Route OPTIONS request

I use Adonis Framework as backend and angularjs for frontend.
My routes:

Route.post('/user/registration', 'UserController.registration');

If i use Adonis on another domain how to resolve OPTIONS request for cross domain ajax?

it request return this headers for me:

Access-Control-Allow-Headers:Content-Type, Authorization
Access-Control-Allow-Methods:GET,PUT,POST,DELETE
Access-Control-Allow-Origin:*
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/user/registration
Request Method:OPTIONS
Status Code:200 OK

Route.any() is ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] only.
Where is OPTIONS?

Hot reload

Is there a way to reload the application changes without restart via npm start ?

Adonis ORM User.all() crashes

Seeing some strange things happening.

When I use the code:

* index (request, response) {
  let users = yield User.all();
  response.json(users);
}

I get an error:

{ [Error: select * from "users" where "users"."deleted_at" is null - SQLITE_ERROR: no such column: users.deleted_at] errno: 1, code: 'SQLITE_ERROR' }

when trying to access my server:

http://localhost:3333/users

However, when I go:

* index (request, response) {
  const users = yield Database.table('users').select('*');
  response.json(users);
}

I get the expected JSON response back without any errors.

I've just discovered Adonis a few hours ago, and taking it for a quick spin.

Also, can we please get some documentation on defining Models in Adonis, I mean setting the properties like username, password, email, and what datatype they're suppose to be etc.

The documentation so far only show how to generate a model using ace command, and how to override special functions such as visible() and hidden().

How do we define our model properties ?

Is it:

class User extends Lucid {
    username: { type: 'string', length: 6 },
    email: { type: 'email' },
    age: { type: 'integer' }
}

Nice framework so far.

What is the preferred way to handle views, based on async data

What is the preferred way to handle views, based on async data? I have a method which returns an promise which gets resolved with the queried data.

// CalendarController.js
* index(request, response) {
    let promise = this.calendarService.loadEvents(access_token);
    promise.then(function(response){
    // how to push data to the view here?
    });
}

soft deletes not working out of box

I am creating a Users schema via migrations, and noticed that it wasn't creating a 'deleted_at' timestamp when using table.timestamps(), so I added the column myself.

exports.up = function(knex, Promise) {
    return Promise.all([
        knex.schema.createTable('users', function(table) {
            table.increments('id')
            table.string('username')
            table.string('firstname')
            table.string('lastname')
            table.string('email')
            table.string('password')
            table.boolean('isadmin').defaultTo('0')
            table.timestamps()
            table.timestamp('deleted_at').nullable().defaultTo(null)
        })
    ])
};

Perhaps this is something that could be added, considering that there are static methods to enable/disable these fields in the framework.

Also, a couple things I noticed about the documentation (not sure if this is the right place to raise these):

  • The documentation for the resourceful controller says that the destroy function is actually named delete http://adonisjs.com/docs/1.0/controllers#resourceful-controllers, while the ace command generates controllers with the function named 'destroy'.
  • Using a query on my Users model to retrieve all users does not ignore those that have a deleted_at timestamp on them and instead have to call fetch() to ignore these rows. Perhaps this is ok but I assumed that because Lucid supports soft deletes out of the box that it would default to use this on a retrieve all query.
  • The documentation surrounding the soft deletes is missing the yield keyword in almost every place it is referenced.

request.flashAll() does not work as expected

Taking this very basic example yield request.flashAll()does not work as expected.

// EventController.js
*index(request, response) {
    let view = yield response.view('event');
    return response.send(view);
}

*add(request, response) {
    console.log(request.all());
    yield request.flashAll();
    let view = yield response.view('event');
    return response.send(view);
}
// routes.js
Route.get('/calendar/event/add/:timestamp', 'EventController.index');
Route.post('/calendar/event/add/:timestamp', 'EventController.add');
<!-- event.html -->
<form method="post">
  <fieldset>
    <div>
      <label for="phone" class="required">Your Phonenumber</label>
      <input type="tel" name="phone" id="phone" value="{{ old('phone') }}">
    </div>
    <div>
      <button class="btn-primary">Submit</button>
    </div>
  </fieldset>
</form>

Okay, whats going on:

  1. User comes to visit /calendar/event/add/:timestamp and gets EventController.index
  2. User fills the form field phone with some input (maybe: lorem)
  3. User clicks submit

Now request.all() looks like that: { phone: 'lorem' } but {{ old('phone') }} is empty.

If he now clicks submit again request.all() looks like that: { phone: '' } but {{ old('phone') }} is now populated with lorem.

Demo

demo

error npm start

hi. i when start projcet with npm start , display this error
...

[email protected] start /home/mostafa/Desktop/test/proje
node --harmony_proxies server.js

Error: Cannot find module './parser'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:286:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object. (/home/mostafa/Desktop/test/proje/node_modules/adonis-validation-provider/node_modules/indicative/lib/validator.js:19:12)
at Object. (/home/mostafa/Desktop/test/proje/node_modules/adonis-validation-provider/node_modules/indicative/lib/validator.js:174:4)
at Module._compile (module.js:430:26)
at Object.Module._extensions..js (module.js:448:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
...

use other provider

i can't use other provider in my provider .... return this error e.g..

Error: Cannot find module 'Validator'

but in controller is not problem for use provider ...

well-done

seems like you've been impressed by laravel)) I see a lot of concepts Laravel follows))
really good done))GL

P.S
nevertheless a lot features still missing but this a good start

How to deal (properly) with services?

If I'm using the following setup, i got an TypeError (500) - AdminService.prefix is not a function. What do i miss here?

// app/Services/AdminService.js
'use strict';
class AdminService {
  *prefix(str) {
    return 'myAwesomePrefix' + str;
  }
}
module.exports = AdminService;
// app/Http/Controllers/AdminController.js
'use strict';
const Database = use('Database');
const AdminService = use('App/Services/AdminService');

class AdminController {
  *save(request, response) {
      let prefixedFormData = yield AdminService.prefix(formData);
      yield Database('admin').insert({name: prefixedFormData});
      response.redirect('admin');
    }
}
module.exports = AdminController;

How do you get following login functionality to work properly?

I've been having some issues with understanding Lucid, and overall api. Documentation is kinda ok but i couldn't find descriptions on api, so i started checking the code.
Can you help me with this. How would you write this? Check for user, session login. Thanks

class AccessController {
  * login(request, response) {
    const rules = {
      username: 'required|email',
      password: 'required|min:6'
    }
    let data = request.post()

    yield Validator.validate(rules, data)

    // checking if validation has failed
    if (Validator.fails()) {
      return Validator.messages()
    }

    let currentUser = yield User.where('username', '=', data.username).fetch();
    currentUser = currentUser.toJSON()[0];
    if (!currentUser.id) {
      response.send(404).json({
        message: 'User not found'
      });
    } else {
      let currentSession = yield Session.where('user_id', '=', currentUser.id).fetch();
      currentSession = currentSession.toJSON();
      console.log(currentSession);
    }
}

Can't serve a fresh install

I have lastest node version installed
nove -v >>> v4.1.0

Then I follow those steps:
npm install -g adonis-cli
adonis new test && cd test
It's ok.

But when I try to launch app with:
node ace server:start

Error: Cannot find module 'adonis-config-provider/providers/ConfigProvider' at Function.Module._resolveFilename (module.js:336:15) at Function.Module._load (module.js:286:25) at Module.require (module.js:365:17) at require (module.js:384:17) at /var/www/illyon/node_modules/adonis-fold/src/Registerar/helpers.js:31:12 at arrayMap (/var/www/illyon/node_modules/adonis-fold/node_modules/lodash/index.js:1406:25) at Function.map (/var/www/illyon/node_modules/adonis-fold/node_modules/lodash/index.js:6710:14) at Object.RegisterarHelpers.requireHash (/var/www/illyon/node_modules/adonis-fold/src/Registerar/helpers.js:30:22) at /var/www/illyon/node_modules/adonis-fold/src/Registerar/index.js:29:35 at Object.Registerar.register (/var/www/illyon/node_modules/adonis-fold/src/Registerar/index.js:27:10)

It seems the 'index.js' file is forgotten into 'adonis-config-provider/providers/ConfigProvider' path.

Sanitize user input

How do we handle user input? Writing a custom service provider or is there an built in way to sanitize user input?

Any guidelines for authentication?

Very exited about v2. amazing work and massive amount of cool ideas.
Are there any guidelines for authentication?
Or maybe some ways to integrate Passport based on connect?

service provider register

how i can register my provider in app...
when i put

const provider = [
....
    path.join(__dirname, '../providers/Challenge/provider.js')
]

this return error ....

Got "ParseError: Unexpected token" while using yield

Pretty sure i did not get the concept of generators, but why the heck I get a parse error in this method?

yield Database.from('admin').insert({access_token: tokens.access_token}); ^ ParseError: Unexpected token

getToken(code) is called from within a controller.
oauth2Client.getToken responds correctly, access_token is properly logged.

Parse error

const Database = use('Database');
const google = require('googleapis');
const googleAuth = require('google-auth-library');

class GoogleCalendarService {

  constructor() {
      let OAuth2 = google.auth.OAuth2;
      this.oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
  }

  * getToken(code) {
    let oauth2Client = this.oauth2Client;
    oauth2Client.getToken(code, function (err, tokens){
      if (!err) {
        oauth2Client.setCredentials(tokens);
        console.log(`Save ${tokens.access_token} to database`);
        //yield Database.from('admin').insert({'access_token': tokens.access_token});
      }
    });
  }
}

Response file download with a specified file name

I am storing the file metadata on the database and the file content on the OS file system.
So I set a unique key from database as filename saved to the disk.

Actually the prototype of Response download method is
response.attachment(path_to_file)
and should be at least
response.attachment(path_to_file[, name])

So I would be able to restore the user original filename while he is downloading it

*download(request,response){
      let file = /*fetch data from db*/
      response.attachment(file.path+file.id+file.format, file.name)
  }

Could you add the possibility to set a filename on the fly for a file to download ?

Because actually without this option the user receive the database file ID as filename
image

Could you set an improvement like the code snippet below ? Also could you add the possibility to set 'Content-Disposition' header to 'inline' or 'attachment' values according to the underlying module ?

  /**
   * Force Download file
   * @param     {String}   |     path                           |     path to file
   * @param     {String}   |     [name]                         |     name
   * @param     {String}   |     [disposition='attachment']     |     Force inline attachment
  */
  Response.prototype.attachment = function(path, name, disposition) {
    name = name || path
    disposition = disposition || 'attachment'
    this.header('Content-Disposition', contentDisposition(name, { type: disposition }))
    this.sendFile(path)
    return this
  };

to adonis-framework/node_modules/node-res/lib/index.js

result
Image

NOTA: Laravel proposes a similar thing

[Error: Unable to locate null session driver]

After running npm start i got the following error: [Error: Unable to locate null session driver]
I intentionally changed nothing related to sessions. It’s also broken when i setup a fresh install using adonis new

LUCID orm lack of relationships

When did you plan to implement model relationships ?
Meantime only the querybuilder is efficient to handle relations so the ORM is not very useful with this lack.

Do you have a release date ?
I want to use your framework for my next project.
Thanks.

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.