Как использовать oembed для отображения плейлиста soundcloud - PullRequest
0 голосов
/ 16 февраля 2019

В моем веб-приложении я хочу, чтобы пользователи добавляли песню или плейлист в свой профиль.

Я знаю, что могу использовать конечную точку ombleed soundcloud, например, если я хочу встроить эту песню:

https://soundcloud.com/giorgiomartini/the-digital-big-bang-wip

Я могу использовать оконечную точку Soundcloud oembed следующим образом:

https://soundcloud.com/oembed?format=json&url=https://soundcloud.com/giorgiomartini/the-digital-big-bang-wip

Итак, на странице профиля пользователя я могу позволить пользователям вводить URL песни и сохранять ее в базе данных как свойство.в модели пользователя.

Так что теперь мне нужно отправить запрос get на ссылку oembed, которая возвращает объект, содержащий iframe, который я мог бы затем показать в профиле пользователя

oembed response:

{
"version": 1,
"type": "rich",
"provider_name": "SoundCloud",
"provider_url": "http://soundcloud.com",
"height": 400,
"width": "100%",
"title": "The Digital Big Bang - [WIP] by Giorgio Martini",
"description": "WIP",
"thumbnail_url": "http://i1.sndcdn.com/artworks-000482165469-5or7d4-t500x500.jpg",
"html": "<iframe width=\"100%\" height=\"400\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?visual=true&url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F568956381&show_artwork=true\"></iframe>",
"author_name": "Giorgio Martini",
"author_url": "https://soundcloud.com/giorgiomartini"
}

Где и как я могу сделать этот запрос?

Должен ли я сделать это на моем контроллере пользователя, на моей функции getUserByslug?

exports.getUserBySlug = async (req, res, next) => {
  const user = await User.findOne({ slug: req.params.slug })
  if (!user) return next();
  res.render('user', { user, title: user.name });
};

Если дакак?с axios?

Или я должен сделать это где-нибудь еще?может на пользовательской модели?

на пользовательской модели:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
const md5 = require('md5');
const validator = require('validator');
const mongodbErrorHandler = require('mongoose-mongodb-errors');
const passportLocalMongoose = require('passport-local-mongoose');
const slug = require('slugs');

const userSchema = new Schema({
  email: {
    type: String,
    unique: true,
    lowercase: true,
    trim: true,
    validate: [validator.isEmail, 'Invalid Email Address'],
    required: 'Please Supply an email address'
  },
  name: {
    type: String,
    required: 'Please supply a name',
    trim: true
  },
  resetPasswordToken: String,
  resetPasswordExpires: Date,
  props: [
    { type: mongoose.Schema.ObjectId, ref: 'User' }
  ],
  // New stuff
  slug: {
    type: String,
    unique: true,
  },
  genres: [String],
  musicLink: String,
  created: {
    type: Date,
    default: Date.now
  },
  location: {
    type: {
      type: String,
      default: 'Point'
    },
    coordinates: [{
      type: Number,
      required: 'You must supply coordinates!'
    }],
    address: {
      type: String,
      required: 'You must supply an address!'
    }
  },
  photo: String,
  microBio: String,
});

userSchema.index({ location: '2dsphere' })

userSchema.virtual('gravatar').get(function() {
  const hash = md5(this.email);
  return `https://gravatar.com/avatar/${hash}?s=200`;
});

userSchema.pre('save', async function(next) {
  // TODO make more resiliant so slugs are unique
  this.slug = slug(this.name);
  next();
});

userSchema.plugin(passportLocalMongoose, { usernameField: 'email' });
userSchema.plugin(mongodbErrorHandler);

module.exports = mongoose.model('User', userSchema);
...