icebob / vue-express-mongo-boilerplate

:star: MEVN Full stack JS web app boilerplate with NodeJS, Express, Mongo and VueJS
http://vemapp.moleculer.services/
2.85k stars 756 forks source link

Skip response sending from core service. #33

Open fizerkhan opened 7 years ago

fizerkhan commented 7 years ago

I want to implement download endpoint for one of the model (eg: posts). I can't do it with current implementation.

May be, you can give an option to exclude response sending for specific action. Instead that particular action send response directory using ctx.res.

icebob commented 7 years ago

Please explain, I don't understand what would you like.

fizerkhan commented 7 years ago

In my app, I want to download contacts in CSV. Currently I can only return the data from the action, so I cannot make it downloadable. So I make a workaround by sending response from action handler itself instead of services.js

download: {
    handler(ctx) {
        return this.actions.find(ctx).
        then( (data) => {
            let fields = ['firstName', 'lastName', 'company', 'company', 'email', 'phone'];
            let fieldNames = ['First Name', 'Last Name', 'Company', 'Title',  'Email', 'Phone'];
            try {
                var result = json2csv({ data: data, fields: fields, fieldNames: fieldNames });
                ctx.res.attachment('Contacts.csv');
                ctx.res.status(200).send(result);
            } catch (err) {
                ctx.res.status(400).json({ error: { message: err.message }, status: 400 });
            }

            return C.DONT_SEND_RESPONSE;
        });
    }
},

In the core/services.js, I just skip the response sending by

  if (json === C.DONT_SEND_RESPONSE) return;
icebob commented 7 years ago

Thanks. Now I understand. I will thinking on it how to implement correctly.

icebob commented 7 years ago

In ice-services branch with Moleculer I will use this solution to handle multiple response types.

fizerkhan commented 7 years ago

@icebob Thats make sense 👍