用头像创建用户

时间:2019-03-24 14:40:31

标签: sails.js sails-postgresql

我想在用户注册中添加一个头像,但我不知道如何,请有人可以和我分享一个完整的示例(表单,JS前端和JS后端)。我在VueJs中使用SailsJS 1.0(稳定版)。 预先感谢。

1 个答案:

答案 0 :(得分:1)

我知道了。观看这些platzi教程:

以下是视频告诉您的操作:

  1. npm i sails-hook-uploads
  2. api/controllers/entrance/signup.js

    1. inputs键上方添加一个新的键/值files: ['avatar'],
    2. inputs中添加:

      avatar: {
          type: 'ref',
          required: true
      }
      
  3. fn的正文中找到var newUserRecord并在此添加项之上(即使不需要头像,也请确保执行此行,否则您将收到“ unconsuemd超时”文件流”:

    const avatarInfo =等待sails.uploadOne(inputs.avatar);

  4. 然后在var newUserRecord = await User.create(_.extend({的第一个参数对象中添加:

    avatarFd: avatarInfo.fd,
    avatarMime: avatarInfo.type
    
  5. api/models/User.js中,将以下属性添加到您的User模型中:

    avatarFd: {
        type: 'string',
        required: false,
        description: 'will either have "text" or "avatarFd"'
    },
    
    avatarMime: {
        type: 'string',
        required: false,
        description: 'required if "avatarFd" provided'
    },  
    
  6. 然后创建一个下载端点,这是操作的外观:

    const user = await User.findOne(id);
    
    this.res.type(paste.photoMime);
    
    const avatarStream = await sails.startDownload(paste.photoFd);
    
    return exits.success(avatarStream);
    
  7. 将此下载化身端点的路由添加到路由中。

  8. 然后您可以通过将<img src="">此处的源指向此下载端点来显示此头像。

------附录-----

---- signup.js -----

module.exports = {


  friendlyName: 'Signup',


  description: 'Sign up for a new user account.',


  extendedDescription:
`This creates a new user record in the database, signs in the requesting user agent
by modifying its [session](https://sailsjs.com/documentation/concepts/sessions), and
(if emailing with Mailgun is enabled) sends an account verification email.

If a verification email is sent, the new user's account is put in an "unconfirmed" state
until they confirm they are using a legitimate email address (by clicking the link in
the account verification message.)`,


  files: ['avatar'],

  inputs: {

    emailAddress: {
      required: true,
      type: 'string',
      isEmail: true,
      description: 'The email address for the new account, e.g. m@example.com.',
      extendedDescription: 'Must be a valid email address.',
    },

    password: {
      required: true,
      type: 'string',
      maxLength: 200,
      example: 'passwordlol',
      description: 'The unencrypted password to use for the new account.'
    },

    fullName:  {
      required: true,
      type: 'string',
      example: 'Frida Kahlo de Rivera',
      description: 'The user\'s full name.',
    },

    avatar: {

    }

  },


  exits: {

    success: {
      description: 'New user account was created successfully.'
    },

    invalid: {
      responseType: 'badRequest',
      description: 'The provided fullName, password and/or email address are invalid.',
      extendedDescription: 'If this request was sent from a graphical user interface, the request '+
      'parameters should have been validated/coerced _before_ they were sent.'
    },

    emailAlreadyInUse: {
      statusCode: 409,
      description: 'The provided email address is already in use.',
    },

  },


  fn: async function (inputs) {

    var newEmailAddress = inputs.emailAddress.toLowerCase();

    // must do this even if inputs.avatar is not required
    const avatarInfo = await sails.uploadOne(inputs.avatar);

    // Build up data for the new user record and save it to the database.
    // (Also use `fetch` to retrieve the new ID so that we can use it below.)
    var newUserRecord = await User.create(_.extend({
      emailAddress: newEmailAddress,
      password: await sails.helpers.passwords.hashPassword(inputs.password),
      fullName: inputs.fullName,
      tosAcceptedByIp: this.req.ip,
      avatarFd: avatarInfo.fd,
      avatarMime: avatarInfo.type
    }, sails.config.custom.verifyEmailAddresses? {
      emailProofToken: await sails.helpers.strings.random('url-friendly'),
      emailProofTokenExpiresAt: Date.now() + sails.config.custom.emailProofTokenTTL,
      emailStatus: 'unconfirmed'
    }:{}))
    .intercept('E_UNIQUE', 'emailAlreadyInUse')
    .intercept({name: 'UsageError'}, 'invalid')
    .fetch();

    // If billing feaures are enabled, save a new customer entry in the Stripe API.
    // Then persist the Stripe customer id in the database.
    if (sails.config.custom.enableBillingFeatures) {
      let stripeCustomerId = await sails.helpers.stripe.saveBillingInfo.with({
        emailAddress: newEmailAddress
      }).timeout(5000).retry();
      await User.updateOne(newUserRecord.id)
      .set({
        stripeCustomerId
      });
    }

    // Store the user's new id in their session.
    this.req.session.userId = newUserRecord.id;

    if (sails.config.custom.verifyEmailAddresses) {
      // Send "confirm account" email
      await sails.helpers.sendTemplateEmail.with({
        to: newEmailAddress,
        subject: 'Please confirm your account',
        template: 'email-verify-account',
        templateData: {
          fullName: inputs.fullName,
          token: newUserRecord.emailProofToken
        }
      });
    } else {
      sails.log.info('Skipping new account email verification... (since `verifyEmailAddresses` is disabled)');
    }

    // add to pubilc group
    const publicGroup = await Group.fetchPublicGroup();
    await Group.addMember(publicGroup.id, newUserRecord.id);


  }

};